bloom-horizontal-reconstitute.vs 340 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570
  1. #version 150
  2. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  3. // crt-royale: A full-featured CRT shader, with cheese.
  4. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  5. //
  6. // This program is free software; you can redistribute it and/or modify it
  7. // under the terms of the GNU General Public License as published by the Free
  8. // Software Foundation; either version 2 of the License, or any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful, but WITHOUT
  11. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  13. // more details.
  14. //
  15. // You should have received a copy of the GNU General Public License along with
  16. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  17. // Place, Suite 330, Boston, MA 02111-1307 USA
  18. in vec4 position;
  19. in vec2 texCoord;
  20. // These things didn't want to function in the vertex, so I just commented them
  21. out Vertex {
  22. vec2 vTexCoord;
  23. // vec2 video_uv;
  24. // vec2 scanline_tex_uv;
  25. // vec2 halation_tex_uv;
  26. // vec2 brightpass_tex_uv;
  27. // vec2 bloom_tex_uv;
  28. vec2 bloom_dxdy;
  29. float bloom_sigma_runtime;
  30. };
  31. uniform vec4 targetSize;
  32. uniform vec4 sourceSize[];
  33. // USER SETTINGS BLOCK //
  34. #define crt_gamma 2.500000
  35. #define lcd_gamma 2.200000
  36. #define levels_contrast 1.0
  37. #define halation_weight 0.0
  38. #define diffusion_weight 0.075
  39. #define bloom_underestimate_levels 0.8
  40. #define bloom_excess 0.000000
  41. #define beam_min_sigma 0.020000
  42. #define beam_max_sigma 0.300000
  43. #define beam_spot_power 0.330000
  44. #define beam_min_shape 2.000000
  45. #define beam_max_shape 4.000000
  46. #define beam_shape_power 0.250000
  47. #define beam_horiz_filter 0.000000
  48. #define beam_horiz_sigma 0.35
  49. #define beam_horiz_linear_rgb_weight 1.000000
  50. #define convergence_offset_x_r -0.000000
  51. #define convergence_offset_x_g 0.000000
  52. #define convergence_offset_x_b 0.000000
  53. #define convergence_offset_y_r 0.000000
  54. #define convergence_offset_y_g -0.000000
  55. #define convergence_offset_y_b 0.000000
  56. #define mask_type 1.000000
  57. #define mask_sample_mode_desired 0.000000
  58. #define mask_specify_num_triads 0.000000
  59. #define mask_triad_size_desired 3.000000
  60. #define mask_num_triads_desired 480.000000
  61. #define aa_subpixel_r_offset_x_runtime -0.0
  62. #define aa_subpixel_r_offset_y_runtime 0.000000
  63. #define aa_cubic_c 0.500000
  64. #define aa_gauss_sigma 0.500000
  65. #define geom_mode_runtime 0.000000
  66. #define geom_radius 2.000000
  67. #define geom_view_dist 2.000000
  68. #define geom_tilt_angle_x 0.000000
  69. #define geom_tilt_angle_y 0.000000
  70. #define geom_aspect_ratio_x 432.000000
  71. #define geom_aspect_ratio_y 329.000000
  72. #define geom_overscan_x 1.000000
  73. #define geom_overscan_y 1.000000
  74. #define border_size 0.015
  75. #define border_darkness 2.0
  76. #define border_compress 2.500000
  77. #define interlace_bff 0.000000
  78. #define interlace_1080i 0.000000
  79. // END USER SETTINGS BLOCK //
  80. // compatibility macros for transparently converting HLSLisms into GLSLisms
  81. #define mul(a,b) (b*a)
  82. #define lerp(a,b,c) mix(a,b,c)
  83. #define saturate(c) clamp(c, 0.0, 1.0)
  84. #define frac(x) (fract(x))
  85. #define float2 vec2
  86. #define float3 vec3
  87. #define float4 vec4
  88. #define bool2 bvec2
  89. #define bool3 bvec3
  90. #define bool4 bvec4
  91. #define float2x2 mat2x2
  92. #define float3x3 mat3x3
  93. #define float4x4 mat4x4
  94. #define float4x3 mat4x3
  95. #define float2x4 mat2x4
  96. #define IN params
  97. #define texture_size sourceSize[0].xy
  98. #define video_size sourceSize[0].xy
  99. #define output_size targetSize.xy
  100. #define frame_count phase
  101. #define static
  102. #define inline
  103. #define const
  104. #define fmod(x,y) mod(x,y)
  105. #define ddx(c) dFdx(c)
  106. #define ddy(c) dFdy(c)
  107. #define atan2(x,y) atan(y,x)
  108. #define rsqrt(c) inversesqrt(c)
  109. #define MASKED_SCANLINEStexture source[2]
  110. #define MASKED_SCANLINEStexture_size sourceSize[2].xy
  111. #define MASKED_SCANLINESvideo_size sourceSize[2].xy
  112. #define HALATION_BLURtexture source[5]
  113. #define HALATION_BLURtexture_size sourceSize[5].xy
  114. #define HALATION_BLURvideo_size sourceSize[5].xy
  115. #define BRIGHTPASStexture source[1]
  116. #define BRIGHTPASStexture_size sourceSize[1].xy
  117. #define BRIGHTPASSvideo_size sourceSize[1].xy
  118. #if defined(GL_ES)
  119. #define COMPAT_PRECISION mediump
  120. #else
  121. #define COMPAT_PRECISION
  122. #endif
  123. #if __VERSION__ >= 130
  124. #define COMPAT_TEXTURE texture
  125. #else
  126. #define COMPAT_TEXTURE texture2D
  127. #endif
  128. ///////////////////////////// SETTINGS MANAGEMENT ////////////////////////////
  129. //#include "../user-settings.h"
  130. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  131. #ifndef USER_SETTINGS_H
  132. #define USER_SETTINGS_H
  133. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  134. // The Cg compiler uses different "profiles" with different capabilities.
  135. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  136. // require higher profiles like fp30 or fp40. The shader can't detect profile
  137. // or driver capabilities, so instead you must comment or uncomment the lines
  138. // below with "//" before "#define." Disable an option if you get compilation
  139. // errors resembling those listed. Generally speaking, all of these options
  140. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  141. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  142. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  143. // Among other things, derivatives help us fix anisotropic filtering artifacts
  144. // with curved manually tiled phosphor mask coords. Related errors:
  145. // error C3004: function "float2 ddx(float2);" not supported in this profile
  146. // error C3004: function "float2 ddy(float2);" not supported in this profile
  147. //#define DRIVERS_ALLOW_DERIVATIVES
  148. // Fine derivatives: Unsupported on older ATI cards.
  149. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  150. // fast single-pass blur operations. If your card uses coarse derivatives and
  151. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  152. #ifdef DRIVERS_ALLOW_DERIVATIVES
  153. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  154. #endif
  155. // Dynamic looping: Requires an fp30 or newer profile.
  156. // This makes phosphor mask resampling faster in some cases. Related errors:
  157. // error C5013: profile does not support "for" statements and "for" could not
  158. // be unrolled
  159. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  160. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  161. // Using one static loop avoids overhead if the user is right, but if the user
  162. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  163. // binary search can potentially save some iterations. However, it may fail:
  164. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  165. // needed to compile program
  166. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  167. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  168. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  169. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  170. // this profile
  171. //#define DRIVERS_ALLOW_TEX2DLOD
  172. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  173. // artifacts from anisotropic filtering and mipmapping. Related errors:
  174. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  175. // in this profile
  176. //#define DRIVERS_ALLOW_TEX2DBIAS
  177. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  178. // impose stricter limitations on register counts and instructions. Enable
  179. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  180. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  181. // to compile program.
  182. // Enabling integrated graphics compatibility mode will automatically disable:
  183. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  184. // (This may be reenabled in a later release.)
  185. // 2.) RUNTIME_GEOMETRY_MODE
  186. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  187. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  188. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  189. // To disable a #define option, turn its line into a comment with "//."
  190. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  191. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  192. // many of the options in this file and allow real-time tuning, but many of
  193. // them are slower. Disabling them and using this text file will boost FPS.
  194. #define RUNTIME_SHADER_PARAMS_ENABLE
  195. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  196. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  197. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  198. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  199. #define RUNTIME_ANTIALIAS_WEIGHTS
  200. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  201. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  202. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  203. // parameters? This will require more math or dynamic branching.
  204. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  205. // Specify the tilt at runtime? This makes things about 3% slower.
  206. #define RUNTIME_GEOMETRY_TILT
  207. // Specify the geometry mode at runtime?
  208. #define RUNTIME_GEOMETRY_MODE
  209. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  210. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  211. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  212. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  213. // PHOSPHOR MASK:
  214. // Manually resize the phosphor mask for best results (slower)? Disabling this
  215. // removes the option to do so, but it may be faster without dynamic branches.
  216. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  217. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  218. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  219. // Larger blurs are expensive, but we need them to blur larger triads. We can
  220. // detect the right blur if the triad size is static or our profile allows
  221. // dynamic branches, but otherwise we use the largest blur the user indicates
  222. // they might need:
  223. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  224. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  225. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  226. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  227. // Here's a helpful chart:
  228. // MaxTriadSize BlurSize MinTriadCountsByResolution
  229. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  230. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  231. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  232. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  233. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  234. /////////////////////////////// USER PARAMETERS //////////////////////////////
  235. // Note: Many of these static parameters are overridden by runtime shader
  236. // parameters when those are enabled. However, many others are static codepath
  237. // options that were cleaner or more convert to code as static constants.
  238. // GAMMA:
  239. static const float crt_gamma_static = 2.5; // range [1, 5]
  240. static const float lcd_gamma_static = 2.2; // range [1, 5]
  241. // LEVELS MANAGEMENT:
  242. // Control the final multiplicative image contrast:
  243. static const float levels_contrast_static = 1.0; // range [0, 4)
  244. // We auto-dim to avoid clipping between passes and restore brightness
  245. // later. Control the dim factor here: Lower values clip less but crush
  246. // blacks more (static only for now).
  247. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  248. // HALATION/DIFFUSION/BLOOM:
  249. // Halation weight: How much energy should be lost to electrons bounding
  250. // around under the CRT glass and exciting random phosphors?
  251. static const float halation_weight_static = 0.0; // range [0, 1]
  252. // Refractive diffusion weight: How much light should spread/diffuse from
  253. // refracting through the CRT glass?
  254. static const float diffusion_weight_static = 0.075; // range [0, 1]
  255. // Underestimate brightness: Bright areas bloom more, but we can base the
  256. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  257. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  258. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  259. // Blur all colors more than necessary for a softer phosphor bloom?
  260. static const float bloom_excess_static = 0.0; // range [0, 1]
  261. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  262. // blurred resize of the input (convergence offsets are applied as well).
  263. // There are three filter options (static option only for now):
  264. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  265. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  266. // and beam_max_sigma is low.
  267. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  268. // always uses a static sigma regardless of beam_max_sigma or
  269. // mask_num_triads_desired.
  270. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  271. // These options are more pronounced for the fast, unbloomed shader version.
  272. #ifndef RADEON_FIX
  273. static const float bloom_approx_filter_static = 2.0;
  274. #else
  275. static const float bloom_approx_filter_static = 1.0;
  276. #endif
  277. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  278. // How many scanlines should contribute light to each pixel? Using more
  279. // scanlines is slower (especially for a generalized Gaussian) but less
  280. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  281. // max_beam_sigma at which the closest unused weight is guaranteed <
  282. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  283. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  284. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  285. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  286. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  287. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  288. static const float beam_num_scanlines = 3.0; // range [2, 6]
  289. // A generalized Gaussian beam varies shape with color too, now just width.
  290. // It's slower but more flexible (static option only for now).
  291. static const bool beam_generalized_gaussian = true;
  292. // What kind of scanline antialiasing do you want?
  293. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  294. // Integrals are slow (especially for generalized Gaussians) and rarely any
  295. // better than 3x antialiasing (static option only for now).
  296. static const float beam_antialias_level = 1.0; // range [0, 2]
  297. // Min/max standard deviations for scanline beams: Higher values widen and
  298. // soften scanlines. Depending on other options, low min sigmas can alias.
  299. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  300. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  301. // Beam width varies as a function of color: A power function (0) is more
  302. // configurable, but a spherical function (1) gives the widest beam
  303. // variability without aliasing (static option only for now).
  304. static const float beam_spot_shape_function = 0.0;
  305. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  306. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  307. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  308. // Generalized Gaussian max shape parameters: Higher values give flatter
  309. // scanline plateaus and steeper dropoffs, simultaneously widening and
  310. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  311. // values > ~40.0 cause artifacts with integrals.
  312. static const float beam_min_shape_static = 2.0; // range [2, 32]
  313. static const float beam_max_shape_static = 4.0; // range [2, 32]
  314. // Generalized Gaussian shape power: Affects how quickly the distribution
  315. // changes shape from Gaussian to steep/plateaued as color increases from 0
  316. // to 1.0. Higher powers appear softer for most colors, and lower powers
  317. // appear sharper for most colors.
  318. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  319. // What filter should be used to sample scanlines horizontally?
  320. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  321. static const float beam_horiz_filter_static = 0.0;
  322. // Standard deviation for horizontal Gaussian resampling:
  323. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  324. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  325. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  326. // limiting circuitry in some CRT's), or a weighted avg.?
  327. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  328. // Simulate scanline misconvergence? This needs 3x horizontal texture
  329. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  330. // later passes (static option only for now).
  331. static const bool beam_misconvergence = true;
  332. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  333. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  334. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  335. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  336. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  337. // Detect interlacing (static option only for now)?
  338. static const bool interlace_detect = true;
  339. // Assume 1080-line sources are interlaced?
  340. static const bool interlace_1080i_static = false;
  341. // For interlaced sources, assume TFF (top-field first) or BFF order?
  342. // (Whether this matters depends on the nature of the interlaced input.)
  343. static const bool interlace_bff_static = false;
  344. // ANTIALIASING:
  345. // What AA level do you want for curvature/overscan/subpixels? Options:
  346. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  347. // (Static option only for now)
  348. static const float aa_level = 12.0; // range [0, 24]
  349. // What antialiasing filter do you want (static option only)? Options:
  350. // 0: Box (separable), 1: Box (cylindrical),
  351. // 2: Tent (separable), 3: Tent (cylindrical),
  352. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  353. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  354. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  355. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  356. static const float aa_filter = 6.0; // range [0, 9]
  357. // Flip the sample grid on odd/even frames (static option only for now)?
  358. static const bool aa_temporal = false;
  359. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  360. // the blue offset is the negative r offset; range [0, 0.5]
  361. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  362. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  363. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  364. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  365. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  366. // 4.) C = 0.0 is a soft spline filter.
  367. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  368. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  369. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  370. // PHOSPHOR MASK:
  371. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  372. static const float mask_type_static = 1.0; // range [0, 2]
  373. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  374. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  375. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  376. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  377. // is halfway decent with LUT mipmapping but atrocious without it.
  378. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  379. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  380. // This mode reuses the same masks, so triads will be enormous unless
  381. // you change the mask LUT filenames in your .cgp file.
  382. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  383. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  384. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  385. // will always be used to calculate the full bloom sigma statically.
  386. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  387. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  388. // triads) will be rounded to the nearest integer tile size and clamped to
  389. // obey minimum size constraints (imposed to reduce downsize taps) and
  390. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  391. // To increase the size limit, double the viewport-relative scales for the
  392. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  393. // range [1, mask_texture_small_size/mask_triads_per_tile]
  394. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  395. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  396. // final size will be rounded and constrained as above); default 480.0
  397. static const float mask_num_triads_desired_static = 480.0;
  398. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  399. // more samples and avoid moire a bit better, but some is unavoidable
  400. // depending on the destination size (static option for now).
  401. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  402. // The mask is resized using a variable number of taps in each dimension,
  403. // but some Cg profiles always fetch a constant number of taps no matter
  404. // what (no dynamic branching). We can limit the maximum number of taps if
  405. // we statically limit the minimum phosphor triad size. Larger values are
  406. // faster, but the limit IS enforced (static option only, forever);
  407. // range [1, mask_texture_small_size/mask_triads_per_tile]
  408. // TODO: Make this 1.0 and compensate with smarter sampling!
  409. static const float mask_min_allowed_triad_size = 2.0;
  410. // GEOMETRY:
  411. // Geometry mode:
  412. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  413. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  414. static const float geom_mode_static = 0.0; // range [0, 3]
  415. // Radius of curvature: Measured in units of your viewport's diagonal size.
  416. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  417. // View dist is the distance from the player to their physical screen, in
  418. // units of the viewport's diagonal size. It controls the field of view.
  419. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  420. // Tilt angle in radians (clockwise around up and right vectors):
  421. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  422. // Aspect ratio: When the true viewport size is unknown, this value is used
  423. // to help convert between the phosphor triad size and count, along with
  424. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  425. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  426. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  427. // default (256/224)*(54/47) = 1.313069909 (see below)
  428. static const float geom_aspect_ratio_static = 1.313069909;
  429. // Before getting into overscan, here's some general aspect ratio info:
  430. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  431. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  432. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  433. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  434. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  435. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  436. // a.) Enable Retroarch's "Crop Overscan"
  437. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  438. // Real consoles use horizontal black padding in the signal, but emulators
  439. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  440. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  441. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  442. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  443. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  444. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  445. // without doing a. or b., but horizontal image borders will be tighter
  446. // than vertical ones, messing up curvature and overscan. Fixing the
  447. // padding first corrects this.
  448. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  449. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  450. // above: Values < 1.0 zoom out; range (0, inf)
  451. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  452. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  453. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  454. // with strong curvature (static option only for now).
  455. static const bool geom_force_correct_tangent_matrix = true;
  456. // BORDERS:
  457. // Rounded border size in texture uv coords:
  458. static const float border_size_static = 0.015; // range [0, 0.5]
  459. // Border darkness: Moderate values darken the border smoothly, and high
  460. // values make the image very dark just inside the border:
  461. static const float border_darkness_static = 2.0; // range [0, inf)
  462. // Border compression: High numbers compress border transitions, narrowing
  463. // the dark border area.
  464. static const float border_compress_static = 2.5; // range [1, inf)
  465. #endif // USER_SETTINGS_H
  466. //////////////////////////// END USER-SETTINGS //////////////////////////
  467. //#include "derived-settings-and-constants.h"
  468. //////////////////// BEGIN DERIVED-SETTINGS-AND-CONSTANTS ////////////////////
  469. #ifndef DERIVED_SETTINGS_AND_CONSTANTS_H
  470. #define DERIVED_SETTINGS_AND_CONSTANTS_H
  471. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  472. // crt-royale: A full-featured CRT shader, with cheese.
  473. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  474. //
  475. // This program is free software; you can redistribute it and/or modify it
  476. // under the terms of the GNU General Public License as published by the Free
  477. // Software Foundation; either version 2 of the License, or any later version.
  478. //
  479. // This program is distributed in the hope that it will be useful, but WITHOUT
  480. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  481. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  482. // more details.
  483. //
  484. // You should have received a copy of the GNU General Public License along with
  485. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  486. // Place, Suite 330, Boston, MA 02111-1307 USA
  487. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  488. // These macros and constants can be used across the whole codebase.
  489. // Unlike the values in user-settings.cgh, end users shouldn't modify these.
  490. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  491. //#include "../user-settings.h"
  492. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  493. #ifndef USER_SETTINGS_H
  494. #define USER_SETTINGS_H
  495. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  496. // The Cg compiler uses different "profiles" with different capabilities.
  497. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  498. // require higher profiles like fp30 or fp40. The shader can't detect profile
  499. // or driver capabilities, so instead you must comment or uncomment the lines
  500. // below with "//" before "#define." Disable an option if you get compilation
  501. // errors resembling those listed. Generally speaking, all of these options
  502. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  503. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  504. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  505. // Among other things, derivatives help us fix anisotropic filtering artifacts
  506. // with curved manually tiled phosphor mask coords. Related errors:
  507. // error C3004: function "float2 ddx(float2);" not supported in this profile
  508. // error C3004: function "float2 ddy(float2);" not supported in this profile
  509. //#define DRIVERS_ALLOW_DERIVATIVES
  510. // Fine derivatives: Unsupported on older ATI cards.
  511. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  512. // fast single-pass blur operations. If your card uses coarse derivatives and
  513. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  514. #ifdef DRIVERS_ALLOW_DERIVATIVES
  515. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  516. #endif
  517. // Dynamic looping: Requires an fp30 or newer profile.
  518. // This makes phosphor mask resampling faster in some cases. Related errors:
  519. // error C5013: profile does not support "for" statements and "for" could not
  520. // be unrolled
  521. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  522. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  523. // Using one static loop avoids overhead if the user is right, but if the user
  524. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  525. // binary search can potentially save some iterations. However, it may fail:
  526. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  527. // needed to compile program
  528. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  529. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  530. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  531. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  532. // this profile
  533. //#define DRIVERS_ALLOW_TEX2DLOD
  534. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  535. // artifacts from anisotropic filtering and mipmapping. Related errors:
  536. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  537. // in this profile
  538. //#define DRIVERS_ALLOW_TEX2DBIAS
  539. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  540. // impose stricter limitations on register counts and instructions. Enable
  541. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  542. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  543. // to compile program.
  544. // Enabling integrated graphics compatibility mode will automatically disable:
  545. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  546. // (This may be reenabled in a later release.)
  547. // 2.) RUNTIME_GEOMETRY_MODE
  548. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  549. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  550. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  551. // To disable a #define option, turn its line into a comment with "//."
  552. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  553. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  554. // many of the options in this file and allow real-time tuning, but many of
  555. // them are slower. Disabling them and using this text file will boost FPS.
  556. #define RUNTIME_SHADER_PARAMS_ENABLE
  557. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  558. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  559. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  560. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  561. #define RUNTIME_ANTIALIAS_WEIGHTS
  562. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  563. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  564. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  565. // parameters? This will require more math or dynamic branching.
  566. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  567. // Specify the tilt at runtime? This makes things about 3% slower.
  568. #define RUNTIME_GEOMETRY_TILT
  569. // Specify the geometry mode at runtime?
  570. #define RUNTIME_GEOMETRY_MODE
  571. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  572. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  573. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  574. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  575. // PHOSPHOR MASK:
  576. // Manually resize the phosphor mask for best results (slower)? Disabling this
  577. // removes the option to do so, but it may be faster without dynamic branches.
  578. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  579. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  580. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  581. // Larger blurs are expensive, but we need them to blur larger triads. We can
  582. // detect the right blur if the triad size is static or our profile allows
  583. // dynamic branches, but otherwise we use the largest blur the user indicates
  584. // they might need:
  585. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  586. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  587. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  588. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  589. // Here's a helpful chart:
  590. // MaxTriadSize BlurSize MinTriadCountsByResolution
  591. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  592. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  593. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  594. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  595. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  596. /////////////////////////////// USER PARAMETERS //////////////////////////////
  597. // Note: Many of these static parameters are overridden by runtime shader
  598. // parameters when those are enabled. However, many others are static codepath
  599. // options that were cleaner or more convert to code as static constants.
  600. // GAMMA:
  601. static const float crt_gamma_static = 2.5; // range [1, 5]
  602. static const float lcd_gamma_static = 2.2; // range [1, 5]
  603. // LEVELS MANAGEMENT:
  604. // Control the final multiplicative image contrast:
  605. static const float levels_contrast_static = 1.0; // range [0, 4)
  606. // We auto-dim to avoid clipping between passes and restore brightness
  607. // later. Control the dim factor here: Lower values clip less but crush
  608. // blacks more (static only for now).
  609. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  610. // HALATION/DIFFUSION/BLOOM:
  611. // Halation weight: How much energy should be lost to electrons bounding
  612. // around under the CRT glass and exciting random phosphors?
  613. static const float halation_weight_static = 0.0; // range [0, 1]
  614. // Refractive diffusion weight: How much light should spread/diffuse from
  615. // refracting through the CRT glass?
  616. static const float diffusion_weight_static = 0.075; // range [0, 1]
  617. // Underestimate brightness: Bright areas bloom more, but we can base the
  618. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  619. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  620. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  621. // Blur all colors more than necessary for a softer phosphor bloom?
  622. static const float bloom_excess_static = 0.0; // range [0, 1]
  623. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  624. // blurred resize of the input (convergence offsets are applied as well).
  625. // There are three filter options (static option only for now):
  626. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  627. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  628. // and beam_max_sigma is low.
  629. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  630. // always uses a static sigma regardless of beam_max_sigma or
  631. // mask_num_triads_desired.
  632. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  633. // These options are more pronounced for the fast, unbloomed shader version.
  634. #ifndef RADEON_FIX
  635. static const float bloom_approx_filter_static = 2.0;
  636. #else
  637. static const float bloom_approx_filter_static = 1.0;
  638. #endif
  639. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  640. // How many scanlines should contribute light to each pixel? Using more
  641. // scanlines is slower (especially for a generalized Gaussian) but less
  642. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  643. // max_beam_sigma at which the closest unused weight is guaranteed <
  644. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  645. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  646. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  647. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  648. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  649. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  650. static const float beam_num_scanlines = 3.0; // range [2, 6]
  651. // A generalized Gaussian beam varies shape with color too, now just width.
  652. // It's slower but more flexible (static option only for now).
  653. static const bool beam_generalized_gaussian = true;
  654. // What kind of scanline antialiasing do you want?
  655. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  656. // Integrals are slow (especially for generalized Gaussians) and rarely any
  657. // better than 3x antialiasing (static option only for now).
  658. static const float beam_antialias_level = 1.0; // range [0, 2]
  659. // Min/max standard deviations for scanline beams: Higher values widen and
  660. // soften scanlines. Depending on other options, low min sigmas can alias.
  661. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  662. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  663. // Beam width varies as a function of color: A power function (0) is more
  664. // configurable, but a spherical function (1) gives the widest beam
  665. // variability without aliasing (static option only for now).
  666. static const float beam_spot_shape_function = 0.0;
  667. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  668. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  669. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  670. // Generalized Gaussian max shape parameters: Higher values give flatter
  671. // scanline plateaus and steeper dropoffs, simultaneously widening and
  672. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  673. // values > ~40.0 cause artifacts with integrals.
  674. static const float beam_min_shape_static = 2.0; // range [2, 32]
  675. static const float beam_max_shape_static = 4.0; // range [2, 32]
  676. // Generalized Gaussian shape power: Affects how quickly the distribution
  677. // changes shape from Gaussian to steep/plateaued as color increases from 0
  678. // to 1.0. Higher powers appear softer for most colors, and lower powers
  679. // appear sharper for most colors.
  680. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  681. // What filter should be used to sample scanlines horizontally?
  682. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  683. static const float beam_horiz_filter_static = 0.0;
  684. // Standard deviation for horizontal Gaussian resampling:
  685. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  686. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  687. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  688. // limiting circuitry in some CRT's), or a weighted avg.?
  689. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  690. // Simulate scanline misconvergence? This needs 3x horizontal texture
  691. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  692. // later passes (static option only for now).
  693. static const bool beam_misconvergence = true;
  694. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  695. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  696. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  697. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  698. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  699. // Detect interlacing (static option only for now)?
  700. static const bool interlace_detect = true;
  701. // Assume 1080-line sources are interlaced?
  702. static const bool interlace_1080i_static = false;
  703. // For interlaced sources, assume TFF (top-field first) or BFF order?
  704. // (Whether this matters depends on the nature of the interlaced input.)
  705. static const bool interlace_bff_static = false;
  706. // ANTIALIASING:
  707. // What AA level do you want for curvature/overscan/subpixels? Options:
  708. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  709. // (Static option only for now)
  710. static const float aa_level = 12.0; // range [0, 24]
  711. // What antialiasing filter do you want (static option only)? Options:
  712. // 0: Box (separable), 1: Box (cylindrical),
  713. // 2: Tent (separable), 3: Tent (cylindrical),
  714. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  715. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  716. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  717. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  718. static const float aa_filter = 6.0; // range [0, 9]
  719. // Flip the sample grid on odd/even frames (static option only for now)?
  720. static const bool aa_temporal = false;
  721. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  722. // the blue offset is the negative r offset; range [0, 0.5]
  723. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  724. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  725. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  726. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  727. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  728. // 4.) C = 0.0 is a soft spline filter.
  729. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  730. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  731. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  732. // PHOSPHOR MASK:
  733. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  734. static const float mask_type_static = 1.0; // range [0, 2]
  735. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  736. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  737. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  738. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  739. // is halfway decent with LUT mipmapping but atrocious without it.
  740. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  741. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  742. // This mode reuses the same masks, so triads will be enormous unless
  743. // you change the mask LUT filenames in your .cgp file.
  744. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  745. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  746. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  747. // will always be used to calculate the full bloom sigma statically.
  748. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  749. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  750. // triads) will be rounded to the nearest integer tile size and clamped to
  751. // obey minimum size constraints (imposed to reduce downsize taps) and
  752. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  753. // To increase the size limit, double the viewport-relative scales for the
  754. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  755. // range [1, mask_texture_small_size/mask_triads_per_tile]
  756. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  757. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  758. // final size will be rounded and constrained as above); default 480.0
  759. static const float mask_num_triads_desired_static = 480.0;
  760. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  761. // more samples and avoid moire a bit better, but some is unavoidable
  762. // depending on the destination size (static option for now).
  763. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  764. // The mask is resized using a variable number of taps in each dimension,
  765. // but some Cg profiles always fetch a constant number of taps no matter
  766. // what (no dynamic branching). We can limit the maximum number of taps if
  767. // we statically limit the minimum phosphor triad size. Larger values are
  768. // faster, but the limit IS enforced (static option only, forever);
  769. // range [1, mask_texture_small_size/mask_triads_per_tile]
  770. // TODO: Make this 1.0 and compensate with smarter sampling!
  771. static const float mask_min_allowed_triad_size = 2.0;
  772. // GEOMETRY:
  773. // Geometry mode:
  774. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  775. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  776. static const float geom_mode_static = 0.0; // range [0, 3]
  777. // Radius of curvature: Measured in units of your viewport's diagonal size.
  778. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  779. // View dist is the distance from the player to their physical screen, in
  780. // units of the viewport's diagonal size. It controls the field of view.
  781. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  782. // Tilt angle in radians (clockwise around up and right vectors):
  783. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  784. // Aspect ratio: When the true viewport size is unknown, this value is used
  785. // to help convert between the phosphor triad size and count, along with
  786. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  787. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  788. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  789. // default (256/224)*(54/47) = 1.313069909 (see below)
  790. static const float geom_aspect_ratio_static = 1.313069909;
  791. // Before getting into overscan, here's some general aspect ratio info:
  792. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  793. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  794. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  795. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  796. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  797. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  798. // a.) Enable Retroarch's "Crop Overscan"
  799. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  800. // Real consoles use horizontal black padding in the signal, but emulators
  801. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  802. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  803. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  804. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  805. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  806. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  807. // without doing a. or b., but horizontal image borders will be tighter
  808. // than vertical ones, messing up curvature and overscan. Fixing the
  809. // padding first corrects this.
  810. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  811. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  812. // above: Values < 1.0 zoom out; range (0, inf)
  813. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  814. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  815. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  816. // with strong curvature (static option only for now).
  817. static const bool geom_force_correct_tangent_matrix = true;
  818. // BORDERS:
  819. // Rounded border size in texture uv coords:
  820. static const float border_size_static = 0.015; // range [0, 0.5]
  821. // Border darkness: Moderate values darken the border smoothly, and high
  822. // values make the image very dark just inside the border:
  823. static const float border_darkness_static = 2.0; // range [0, inf)
  824. // Border compression: High numbers compress border transitions, narrowing
  825. // the dark border area.
  826. static const float border_compress_static = 2.5; // range [1, inf)
  827. #endif // USER_SETTINGS_H
  828. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  829. //#include "user-cgp-constants.h"
  830. ///////////////////////// BEGIN USER-CGP-CONSTANTS /////////////////////////
  831. #ifndef USER_CGP_CONSTANTS_H
  832. #define USER_CGP_CONSTANTS_H
  833. // IMPORTANT:
  834. // These constants MUST be set appropriately for the settings in crt-royale.cgp
  835. // (or whatever related .cgp file you're using). If they aren't, you're likely
  836. // to get artifacts, the wrong phosphor mask size, etc. I wish these could be
  837. // set directly in the .cgp file to make things easier, but...they can't.
  838. // PASS SCALES AND RELATED CONSTANTS:
  839. // Copy the absolute scale_x for BLOOM_APPROX. There are two major versions of
  840. // this shader: One does a viewport-scale bloom, and the other skips it. The
  841. // latter benefits from a higher bloom_approx_scale_x, so save both separately:
  842. static const float bloom_approx_size_x = 320.0;
  843. static const float bloom_approx_size_x_for_fake = 400.0;
  844. // Copy the viewport-relative scales of the phosphor mask resize passes
  845. // (MASK_RESIZE and the pass immediately preceding it):
  846. static const float2 mask_resize_viewport_scale = float2(0.0625, 0.0625);
  847. // Copy the geom_max_aspect_ratio used to calculate the MASK_RESIZE scales, etc.:
  848. static const float geom_max_aspect_ratio = 4.0/3.0;
  849. // PHOSPHOR MASK TEXTURE CONSTANTS:
  850. // Set the following constants to reflect the properties of the phosphor mask
  851. // texture named in crt-royale.cgp. The shader optionally resizes a mask tile
  852. // based on user settings, then repeats a single tile until filling the screen.
  853. // The shader must know the input texture size (default 64x64), and to manually
  854. // resize, it must also know the horizontal triads per tile (default 8).
  855. static const float2 mask_texture_small_size = float2(64.0, 64.0);
  856. static const float2 mask_texture_large_size = float2(512.0, 512.0);
  857. static const float mask_triads_per_tile = 8.0;
  858. // We need the average brightness of the phosphor mask to compensate for the
  859. // dimming it causes. The following four values are roughly correct for the
  860. // masks included with the shader. Update the value for any LUT texture you
  861. // change. [Un]comment "#define PHOSPHOR_MASK_GRILLE14" depending on whether
  862. // the loaded aperture grille uses 14-pixel or 15-pixel stripes (default 15).
  863. //#define PHOSPHOR_MASK_GRILLE14
  864. static const float mask_grille14_avg_color = 50.6666666/255.0;
  865. // TileableLinearApertureGrille14Wide7d33Spacing*.png
  866. // TileableLinearApertureGrille14Wide10And6Spacing*.png
  867. static const float mask_grille15_avg_color = 53.0/255.0;
  868. // TileableLinearApertureGrille15Wide6d33Spacing*.png
  869. // TileableLinearApertureGrille15Wide8And5d5Spacing*.png
  870. static const float mask_slot_avg_color = 46.0/255.0;
  871. // TileableLinearSlotMask15Wide9And4d5Horizontal8VerticalSpacing*.png
  872. // TileableLinearSlotMaskTall15Wide9And4d5Horizontal9d14VerticalSpacing*.png
  873. static const float mask_shadow_avg_color = 41.0/255.0;
  874. // TileableLinearShadowMask*.png
  875. // TileableLinearShadowMaskEDP*.png
  876. #ifdef PHOSPHOR_MASK_GRILLE14
  877. static const float mask_grille_avg_color = mask_grille14_avg_color;
  878. #else
  879. static const float mask_grille_avg_color = mask_grille15_avg_color;
  880. #endif
  881. #endif // USER_CGP_CONSTANTS_H
  882. ////////////////////////// END USER-CGP-CONSTANTS //////////////////////////
  883. //////////////////////////////// END INCLUDES ////////////////////////////////
  884. /////////////////////////////// FIXED SETTINGS ///////////////////////////////
  885. // Avoid dividing by zero; using a macro overloads for float, float2, etc.:
  886. #define FIX_ZERO(c) (max(abs(c), 0.0000152587890625)) // 2^-16
  887. // Ensure the first pass decodes CRT gamma and the last encodes LCD gamma.
  888. #ifndef SIMULATE_CRT_ON_LCD
  889. #define SIMULATE_CRT_ON_LCD
  890. #endif
  891. // Manually tiling a manually resized texture creates texture coord derivative
  892. // discontinuities and confuses anisotropic filtering, causing discolored tile
  893. // seams in the phosphor mask. Workarounds:
  894. // a.) Using tex2Dlod disables anisotropic filtering for tiled masks. It's
  895. // downgraded to tex2Dbias without DRIVERS_ALLOW_TEX2DLOD #defined and
  896. // disabled without DRIVERS_ALLOW_TEX2DBIAS #defined either.
  897. // b.) "Tile flat twice" requires drawing two full tiles without border padding
  898. // to the resized mask FBO, and it's incompatible with same-pass curvature.
  899. // (Same-pass curvature isn't used but could be in the future...maybe.)
  900. // c.) "Fix discontinuities" requires derivatives and drawing one tile with
  901. // border padding to the resized mask FBO, but it works with same-pass
  902. // curvature. It's disabled without DRIVERS_ALLOW_DERIVATIVES #defined.
  903. // Precedence: a, then, b, then c (if multiple strategies are #defined).
  904. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD // 129.7 FPS, 4x, flat; 101.8 at fullscreen
  905. #define ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE // 128.1 FPS, 4x, flat; 101.5 at fullscreen
  906. #define ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES // 124.4 FPS, 4x, flat; 97.4 at fullscreen
  907. // Also, manually resampling the phosphor mask is slightly blurrier with
  908. // anisotropic filtering. (Resampling with mipmapping is even worse: It
  909. // creates artifacts, but only with the fully bloomed shader.) The difference
  910. // is subtle with small triads, but you can fix it for a small cost.
  911. //#define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  912. ////////////////////////////// DERIVED SETTINGS //////////////////////////////
  913. // Intel HD 4000 GPU's can't handle manual mask resizing (for now), setting the
  914. // geometry mode at runtime, or a 4x4 true Gaussian resize. Disable
  915. // incompatible settings ASAP. (INTEGRATED_GRAPHICS_COMPATIBILITY_MODE may be
  916. // #defined by either user-settings.h or a wrapper .cg that #includes the
  917. // current .cg pass.)
  918. #ifdef INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  919. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  920. #undef PHOSPHOR_MASK_MANUALLY_RESIZE
  921. #endif
  922. #ifdef RUNTIME_GEOMETRY_MODE
  923. #undef RUNTIME_GEOMETRY_MODE
  924. #endif
  925. // Mode 2 (4x4 Gaussian resize) won't work, and mode 1 (3x3 blur) is
  926. // inferior in most cases, so replace 2.0 with 0.0:
  927. static const float bloom_approx_filter =
  928. bloom_approx_filter_static > 1.5 ? 0.0 : bloom_approx_filter_static;
  929. #else
  930. static const float bloom_approx_filter = bloom_approx_filter_static;
  931. #endif
  932. // Disable slow runtime paths if static parameters are used. Most of these
  933. // won't be a problem anyway once the params are disabled, but some will.
  934. #ifndef RUNTIME_SHADER_PARAMS_ENABLE
  935. #ifdef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  936. #undef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  937. #endif
  938. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  939. #undef RUNTIME_ANTIALIAS_WEIGHTS
  940. #endif
  941. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  942. #undef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  943. #endif
  944. #ifdef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  945. #undef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  946. #endif
  947. #ifdef RUNTIME_GEOMETRY_TILT
  948. #undef RUNTIME_GEOMETRY_TILT
  949. #endif
  950. #ifdef RUNTIME_GEOMETRY_MODE
  951. #undef RUNTIME_GEOMETRY_MODE
  952. #endif
  953. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  954. #undef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  955. #endif
  956. #endif
  957. // Make tex2Dbias a backup for tex2Dlod for wider compatibility.
  958. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  959. #define ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  960. #endif
  961. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  962. #define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  963. #endif
  964. // Rule out unavailable anisotropic compatibility strategies:
  965. #ifndef DRIVERS_ALLOW_DERIVATIVES
  966. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  967. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  968. #endif
  969. #endif
  970. #ifndef DRIVERS_ALLOW_TEX2DLOD
  971. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  972. #undef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  973. #endif
  974. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  975. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  976. #endif
  977. #ifdef ANTIALIAS_DISABLE_ANISOTROPIC
  978. #undef ANTIALIAS_DISABLE_ANISOTROPIC
  979. #endif
  980. #endif
  981. #ifndef DRIVERS_ALLOW_TEX2DBIAS
  982. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  983. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  984. #endif
  985. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  986. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  987. #endif
  988. #endif
  989. // Prioritize anisotropic tiling compatibility strategies by performance and
  990. // disable unused strategies. This concentrates all the nesting in one place.
  991. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  992. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  993. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  994. #endif
  995. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  996. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  997. #endif
  998. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  999. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1000. #endif
  1001. #else
  1002. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1003. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1004. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1005. #endif
  1006. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1007. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1008. #endif
  1009. #else
  1010. // ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE is only compatible with
  1011. // flat texture coords in the same pass, but that's all we use.
  1012. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1013. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1014. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1015. #endif
  1016. #endif
  1017. #endif
  1018. #endif
  1019. // The tex2Dlod and tex2Dbias strategies share a lot in common, and we can
  1020. // reduce some #ifdef nesting in the next section by essentially OR'ing them:
  1021. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  1022. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1023. #endif
  1024. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1025. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1026. #endif
  1027. // Prioritize anisotropic resampling compatibility strategies the same way:
  1028. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1029. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  1030. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  1031. #endif
  1032. #endif
  1033. /////////////////////// DERIVED PHOSPHOR MASK CONSTANTS //////////////////////
  1034. // If we can use the large mipmapped LUT without mipmapping artifacts, we
  1035. // should: It gives us more options for using fewer samples.
  1036. #ifdef DRIVERS_ALLOW_TEX2DLOD
  1037. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1038. // TODO: Take advantage of this!
  1039. #define PHOSPHOR_MASK_RESIZE_MIPMAPPED_LUT
  1040. static const float2 mask_resize_src_lut_size = mask_texture_large_size;
  1041. #else
  1042. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  1043. #endif
  1044. #else
  1045. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  1046. #endif
  1047. // tex2D's sampler2D parameter MUST be a uniform global, a uniform input to
  1048. // main_fragment, or a static alias of one of the above. This makes it hard
  1049. // to select the phosphor mask at runtime: We can't even assign to a uniform
  1050. // global in the vertex shader or select a sampler2D in the vertex shader and
  1051. // pass it to the fragment shader (even with explicit TEXUNIT# bindings),
  1052. // because it just gives us the input texture or a black screen. However, we
  1053. // can get around these limitations by calling tex2D three times with different
  1054. // uniform samplers (or resizing the phosphor mask three times altogether).
  1055. // With dynamic branches, we can process only one of these branches on top of
  1056. // quickly discarding fragments we don't need (cgc seems able to overcome
  1057. // limigations around dependent texture fetches inside of branches). Without
  1058. // dynamic branches, we have to process every branch for every fragment...which
  1059. // is slower. Runtime sampling mode selection is slower without dynamic
  1060. // branches as well. Let the user's static #defines decide if it's worth it.
  1061. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  1062. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1063. #else
  1064. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1065. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1066. #endif
  1067. #endif
  1068. // We need to render some minimum number of tiles in the resize passes.
  1069. // We need at least 1.0 just to repeat a single tile, and we need extra
  1070. // padding beyond that for anisotropic filtering, discontinuitity fixing,
  1071. // antialiasing, same-pass curvature (not currently used), etc. First
  1072. // determine how many border texels and tiles we need, based on how the result
  1073. // will be sampled:
  1074. #ifdef GEOMETRY_EARLY
  1075. static const float max_subpixel_offset = aa_subpixel_r_offset_static.x;
  1076. // Most antialiasing filters have a base radius of 4.0 pixels:
  1077. static const float max_aa_base_pixel_border = 4.0 +
  1078. max_subpixel_offset;
  1079. #else
  1080. static const float max_aa_base_pixel_border = 0.0;
  1081. #endif
  1082. // Anisotropic filtering adds about 0.5 to the pixel border:
  1083. #ifndef ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1084. static const float max_aniso_pixel_border = max_aa_base_pixel_border + 0.5;
  1085. #else
  1086. static const float max_aniso_pixel_border = max_aa_base_pixel_border;
  1087. #endif
  1088. // Fixing discontinuities adds 1.0 more to the pixel border:
  1089. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1090. static const float max_tiled_pixel_border = max_aniso_pixel_border + 1.0;
  1091. #else
  1092. static const float max_tiled_pixel_border = max_aniso_pixel_border;
  1093. #endif
  1094. // Convert the pixel border to an integer texel border. Assume same-pass
  1095. // curvature about triples the texel frequency:
  1096. #ifdef GEOMETRY_EARLY
  1097. static const float max_mask_texel_border =
  1098. ceil(max_tiled_pixel_border * 3.0);
  1099. #else
  1100. static const float max_mask_texel_border = ceil(max_tiled_pixel_border);
  1101. #endif
  1102. // Convert the texel border to a tile border using worst-case assumptions:
  1103. static const float max_mask_tile_border = max_mask_texel_border/
  1104. (mask_min_allowed_triad_size * mask_triads_per_tile);
  1105. // Finally, set the number of resized tiles to render to MASK_RESIZE, and set
  1106. // the starting texel (inside borders) for sampling it.
  1107. #ifndef GEOMETRY_EARLY
  1108. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1109. // Special case: Render two tiles without borders. Anisotropic
  1110. // filtering doesn't seem to be a problem here.
  1111. static const float mask_resize_num_tiles = 1.0 + 1.0;
  1112. static const float mask_start_texels = 0.0;
  1113. #else
  1114. static const float mask_resize_num_tiles = 1.0 +
  1115. 2.0 * max_mask_tile_border;
  1116. static const float mask_start_texels = max_mask_texel_border;
  1117. #endif
  1118. #else
  1119. static const float mask_resize_num_tiles = 1.0 + 2.0*max_mask_tile_border;
  1120. static const float mask_start_texels = max_mask_texel_border;
  1121. #endif
  1122. // We have to fit mask_resize_num_tiles into an FBO with a viewport scale of
  1123. // mask_resize_viewport_scale. This limits the maximum final triad size.
  1124. // Estimate the minimum number of triads we can split the screen into in each
  1125. // dimension (we'll be as correct as mask_resize_viewport_scale is):
  1126. static const float mask_resize_num_triads =
  1127. mask_resize_num_tiles * mask_triads_per_tile;
  1128. static const float2 min_allowed_viewport_triads =
  1129. float2(mask_resize_num_triads) / mask_resize_viewport_scale;
  1130. //////////////////////// COMMON MATHEMATICAL CONSTANTS ///////////////////////
  1131. static const float pi = 3.141592653589;
  1132. // We often want to find the location of the previous texel, e.g.:
  1133. // const float2 curr_texel = uv * texture_size;
  1134. // const float2 prev_texel = floor(curr_texel - float2(0.5)) + float2(0.5);
  1135. // const float2 prev_texel_uv = prev_texel / texture_size;
  1136. // However, many GPU drivers round incorrectly around exact texel locations.
  1137. // We need to subtract a little less than 0.5 before flooring, and some GPU's
  1138. // require this value to be farther from 0.5 than others; define it here.
  1139. // const float2 prev_texel =
  1140. // floor(curr_texel - float2(under_half)) + float2(0.5);
  1141. static const float under_half = 0.4995;
  1142. #endif // DERIVED_SETTINGS_AND_CONSTANTS_H
  1143. ///////////////////////////// END DERIVED-SETTINGS-AND-CONSTANTS ////////////////////////////
  1144. //#include "bind-shader-params.h"
  1145. ///////////////////////////// BEGIN BIND-SHADER-PARAMS ////////////////////////////
  1146. #ifndef BIND_SHADER_PARAMS_H
  1147. #define BIND_SHADER_PARAMS_H
  1148. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  1149. // crt-royale: A full-featured CRT shader, with cheese.
  1150. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  1151. //
  1152. // This program is free software; you can redistribute it and/or modify it
  1153. // under the terms of the GNU General Public License as published by the Free
  1154. // Software Foundation; either version 2 of the License, or any later version.
  1155. //
  1156. // This program is distributed in the hope that it will be useful, but WITHOUT
  1157. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  1158. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  1159. // more details.
  1160. //
  1161. // You should have received a copy of the GNU General Public License along with
  1162. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  1163. // Place, Suite 330, Boston, MA 02111-1307 USA
  1164. ///////////////////////////// SETTINGS MANAGEMENT ////////////////////////////
  1165. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  1166. //#include "../user-settings.h"
  1167. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  1168. #ifndef USER_SETTINGS_H
  1169. #define USER_SETTINGS_H
  1170. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  1171. // The Cg compiler uses different "profiles" with different capabilities.
  1172. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  1173. // require higher profiles like fp30 or fp40. The shader can't detect profile
  1174. // or driver capabilities, so instead you must comment or uncomment the lines
  1175. // below with "//" before "#define." Disable an option if you get compilation
  1176. // errors resembling those listed. Generally speaking, all of these options
  1177. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  1178. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  1179. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  1180. // Among other things, derivatives help us fix anisotropic filtering artifacts
  1181. // with curved manually tiled phosphor mask coords. Related errors:
  1182. // error C3004: function "float2 ddx(float2);" not supported in this profile
  1183. // error C3004: function "float2 ddy(float2);" not supported in this profile
  1184. //#define DRIVERS_ALLOW_DERIVATIVES
  1185. // Fine derivatives: Unsupported on older ATI cards.
  1186. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  1187. // fast single-pass blur operations. If your card uses coarse derivatives and
  1188. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  1189. #ifdef DRIVERS_ALLOW_DERIVATIVES
  1190. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  1191. #endif
  1192. // Dynamic looping: Requires an fp30 or newer profile.
  1193. // This makes phosphor mask resampling faster in some cases. Related errors:
  1194. // error C5013: profile does not support "for" statements and "for" could not
  1195. // be unrolled
  1196. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  1197. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  1198. // Using one static loop avoids overhead if the user is right, but if the user
  1199. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  1200. // binary search can potentially save some iterations. However, it may fail:
  1201. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  1202. // needed to compile program
  1203. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  1204. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  1205. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  1206. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  1207. // this profile
  1208. //#define DRIVERS_ALLOW_TEX2DLOD
  1209. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  1210. // artifacts from anisotropic filtering and mipmapping. Related errors:
  1211. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  1212. // in this profile
  1213. //#define DRIVERS_ALLOW_TEX2DBIAS
  1214. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  1215. // impose stricter limitations on register counts and instructions. Enable
  1216. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  1217. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  1218. // to compile program.
  1219. // Enabling integrated graphics compatibility mode will automatically disable:
  1220. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  1221. // (This may be reenabled in a later release.)
  1222. // 2.) RUNTIME_GEOMETRY_MODE
  1223. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  1224. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  1225. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  1226. // To disable a #define option, turn its line into a comment with "//."
  1227. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  1228. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  1229. // many of the options in this file and allow real-time tuning, but many of
  1230. // them are slower. Disabling them and using this text file will boost FPS.
  1231. #define RUNTIME_SHADER_PARAMS_ENABLE
  1232. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  1233. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  1234. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  1235. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  1236. #define RUNTIME_ANTIALIAS_WEIGHTS
  1237. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  1238. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1239. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  1240. // parameters? This will require more math or dynamic branching.
  1241. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  1242. // Specify the tilt at runtime? This makes things about 3% slower.
  1243. #define RUNTIME_GEOMETRY_TILT
  1244. // Specify the geometry mode at runtime?
  1245. #define RUNTIME_GEOMETRY_MODE
  1246. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  1247. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  1248. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  1249. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1250. // PHOSPHOR MASK:
  1251. // Manually resize the phosphor mask for best results (slower)? Disabling this
  1252. // removes the option to do so, but it may be faster without dynamic branches.
  1253. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  1254. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  1255. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  1256. // Larger blurs are expensive, but we need them to blur larger triads. We can
  1257. // detect the right blur if the triad size is static or our profile allows
  1258. // dynamic branches, but otherwise we use the largest blur the user indicates
  1259. // they might need:
  1260. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  1261. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  1262. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  1263. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  1264. // Here's a helpful chart:
  1265. // MaxTriadSize BlurSize MinTriadCountsByResolution
  1266. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1267. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1268. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1269. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1270. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1271. /////////////////////////////// USER PARAMETERS //////////////////////////////
  1272. // Note: Many of these static parameters are overridden by runtime shader
  1273. // parameters when those are enabled. However, many others are static codepath
  1274. // options that were cleaner or more convert to code as static constants.
  1275. // GAMMA:
  1276. static const float crt_gamma_static = 2.5; // range [1, 5]
  1277. static const float lcd_gamma_static = 2.2; // range [1, 5]
  1278. // LEVELS MANAGEMENT:
  1279. // Control the final multiplicative image contrast:
  1280. static const float levels_contrast_static = 1.0; // range [0, 4)
  1281. // We auto-dim to avoid clipping between passes and restore brightness
  1282. // later. Control the dim factor here: Lower values clip less but crush
  1283. // blacks more (static only for now).
  1284. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  1285. // HALATION/DIFFUSION/BLOOM:
  1286. // Halation weight: How much energy should be lost to electrons bounding
  1287. // around under the CRT glass and exciting random phosphors?
  1288. static const float halation_weight_static = 0.0; // range [0, 1]
  1289. // Refractive diffusion weight: How much light should spread/diffuse from
  1290. // refracting through the CRT glass?
  1291. static const float diffusion_weight_static = 0.075; // range [0, 1]
  1292. // Underestimate brightness: Bright areas bloom more, but we can base the
  1293. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  1294. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  1295. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  1296. // Blur all colors more than necessary for a softer phosphor bloom?
  1297. static const float bloom_excess_static = 0.0; // range [0, 1]
  1298. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  1299. // blurred resize of the input (convergence offsets are applied as well).
  1300. // There are three filter options (static option only for now):
  1301. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  1302. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  1303. // and beam_max_sigma is low.
  1304. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  1305. // always uses a static sigma regardless of beam_max_sigma or
  1306. // mask_num_triads_desired.
  1307. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  1308. // These options are more pronounced for the fast, unbloomed shader version.
  1309. #ifndef RADEON_FIX
  1310. static const float bloom_approx_filter_static = 2.0;
  1311. #else
  1312. static const float bloom_approx_filter_static = 1.0;
  1313. #endif
  1314. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  1315. // How many scanlines should contribute light to each pixel? Using more
  1316. // scanlines is slower (especially for a generalized Gaussian) but less
  1317. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  1318. // max_beam_sigma at which the closest unused weight is guaranteed <
  1319. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  1320. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  1321. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  1322. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  1323. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  1324. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  1325. static const float beam_num_scanlines = 3.0; // range [2, 6]
  1326. // A generalized Gaussian beam varies shape with color too, now just width.
  1327. // It's slower but more flexible (static option only for now).
  1328. static const bool beam_generalized_gaussian = true;
  1329. // What kind of scanline antialiasing do you want?
  1330. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  1331. // Integrals are slow (especially for generalized Gaussians) and rarely any
  1332. // better than 3x antialiasing (static option only for now).
  1333. static const float beam_antialias_level = 1.0; // range [0, 2]
  1334. // Min/max standard deviations for scanline beams: Higher values widen and
  1335. // soften scanlines. Depending on other options, low min sigmas can alias.
  1336. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  1337. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  1338. // Beam width varies as a function of color: A power function (0) is more
  1339. // configurable, but a spherical function (1) gives the widest beam
  1340. // variability without aliasing (static option only for now).
  1341. static const float beam_spot_shape_function = 0.0;
  1342. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  1343. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  1344. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  1345. // Generalized Gaussian max shape parameters: Higher values give flatter
  1346. // scanline plateaus and steeper dropoffs, simultaneously widening and
  1347. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  1348. // values > ~40.0 cause artifacts with integrals.
  1349. static const float beam_min_shape_static = 2.0; // range [2, 32]
  1350. static const float beam_max_shape_static = 4.0; // range [2, 32]
  1351. // Generalized Gaussian shape power: Affects how quickly the distribution
  1352. // changes shape from Gaussian to steep/plateaued as color increases from 0
  1353. // to 1.0. Higher powers appear softer for most colors, and lower powers
  1354. // appear sharper for most colors.
  1355. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  1356. // What filter should be used to sample scanlines horizontally?
  1357. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  1358. static const float beam_horiz_filter_static = 0.0;
  1359. // Standard deviation for horizontal Gaussian resampling:
  1360. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  1361. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  1362. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  1363. // limiting circuitry in some CRT's), or a weighted avg.?
  1364. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  1365. // Simulate scanline misconvergence? This needs 3x horizontal texture
  1366. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  1367. // later passes (static option only for now).
  1368. static const bool beam_misconvergence = true;
  1369. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  1370. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  1371. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  1372. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  1373. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  1374. // Detect interlacing (static option only for now)?
  1375. static const bool interlace_detect = true;
  1376. // Assume 1080-line sources are interlaced?
  1377. static const bool interlace_1080i_static = false;
  1378. // For interlaced sources, assume TFF (top-field first) or BFF order?
  1379. // (Whether this matters depends on the nature of the interlaced input.)
  1380. static const bool interlace_bff_static = false;
  1381. // ANTIALIASING:
  1382. // What AA level do you want for curvature/overscan/subpixels? Options:
  1383. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  1384. // (Static option only for now)
  1385. static const float aa_level = 12.0; // range [0, 24]
  1386. // What antialiasing filter do you want (static option only)? Options:
  1387. // 0: Box (separable), 1: Box (cylindrical),
  1388. // 2: Tent (separable), 3: Tent (cylindrical),
  1389. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  1390. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  1391. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  1392. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  1393. static const float aa_filter = 6.0; // range [0, 9]
  1394. // Flip the sample grid on odd/even frames (static option only for now)?
  1395. static const bool aa_temporal = false;
  1396. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  1397. // the blue offset is the negative r offset; range [0, 0.5]
  1398. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  1399. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  1400. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  1401. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  1402. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  1403. // 4.) C = 0.0 is a soft spline filter.
  1404. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  1405. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  1406. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  1407. // PHOSPHOR MASK:
  1408. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  1409. static const float mask_type_static = 1.0; // range [0, 2]
  1410. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  1411. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  1412. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  1413. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  1414. // is halfway decent with LUT mipmapping but atrocious without it.
  1415. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  1416. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  1417. // This mode reuses the same masks, so triads will be enormous unless
  1418. // you change the mask LUT filenames in your .cgp file.
  1419. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  1420. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  1421. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  1422. // will always be used to calculate the full bloom sigma statically.
  1423. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  1424. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  1425. // triads) will be rounded to the nearest integer tile size and clamped to
  1426. // obey minimum size constraints (imposed to reduce downsize taps) and
  1427. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  1428. // To increase the size limit, double the viewport-relative scales for the
  1429. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  1430. // range [1, mask_texture_small_size/mask_triads_per_tile]
  1431. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  1432. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  1433. // final size will be rounded and constrained as above); default 480.0
  1434. static const float mask_num_triads_desired_static = 480.0;
  1435. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  1436. // more samples and avoid moire a bit better, but some is unavoidable
  1437. // depending on the destination size (static option for now).
  1438. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  1439. // The mask is resized using a variable number of taps in each dimension,
  1440. // but some Cg profiles always fetch a constant number of taps no matter
  1441. // what (no dynamic branching). We can limit the maximum number of taps if
  1442. // we statically limit the minimum phosphor triad size. Larger values are
  1443. // faster, but the limit IS enforced (static option only, forever);
  1444. // range [1, mask_texture_small_size/mask_triads_per_tile]
  1445. // TODO: Make this 1.0 and compensate with smarter sampling!
  1446. static const float mask_min_allowed_triad_size = 2.0;
  1447. // GEOMETRY:
  1448. // Geometry mode:
  1449. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  1450. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  1451. static const float geom_mode_static = 0.0; // range [0, 3]
  1452. // Radius of curvature: Measured in units of your viewport's diagonal size.
  1453. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  1454. // View dist is the distance from the player to their physical screen, in
  1455. // units of the viewport's diagonal size. It controls the field of view.
  1456. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  1457. // Tilt angle in radians (clockwise around up and right vectors):
  1458. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  1459. // Aspect ratio: When the true viewport size is unknown, this value is used
  1460. // to help convert between the phosphor triad size and count, along with
  1461. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  1462. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  1463. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  1464. // default (256/224)*(54/47) = 1.313069909 (see below)
  1465. static const float geom_aspect_ratio_static = 1.313069909;
  1466. // Before getting into overscan, here's some general aspect ratio info:
  1467. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  1468. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  1469. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  1470. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  1471. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  1472. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  1473. // a.) Enable Retroarch's "Crop Overscan"
  1474. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  1475. // Real consoles use horizontal black padding in the signal, but emulators
  1476. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  1477. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  1478. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  1479. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  1480. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  1481. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  1482. // without doing a. or b., but horizontal image borders will be tighter
  1483. // than vertical ones, messing up curvature and overscan. Fixing the
  1484. // padding first corrects this.
  1485. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  1486. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  1487. // above: Values < 1.0 zoom out; range (0, inf)
  1488. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  1489. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  1490. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  1491. // with strong curvature (static option only for now).
  1492. static const bool geom_force_correct_tangent_matrix = true;
  1493. // BORDERS:
  1494. // Rounded border size in texture uv coords:
  1495. static const float border_size_static = 0.015; // range [0, 0.5]
  1496. // Border darkness: Moderate values darken the border smoothly, and high
  1497. // values make the image very dark just inside the border:
  1498. static const float border_darkness_static = 2.0; // range [0, inf)
  1499. // Border compression: High numbers compress border transitions, narrowing
  1500. // the dark border area.
  1501. static const float border_compress_static = 2.5; // range [1, inf)
  1502. #endif // USER_SETTINGS_H
  1503. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  1504. //#include "derived-settings-and-constants.h"
  1505. ///////////////////// BEGIN DERIVED-SETTINGS-AND-CONSTANTS ////////////////////
  1506. #ifndef DERIVED_SETTINGS_AND_CONSTANTS_H
  1507. #define DERIVED_SETTINGS_AND_CONSTANTS_H
  1508. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  1509. // crt-royale: A full-featured CRT shader, with cheese.
  1510. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  1511. //
  1512. // This program is free software; you can redistribute it and/or modify it
  1513. // under the terms of the GNU General Public License as published by the Free
  1514. // Software Foundation; either version 2 of the License, or any later version.
  1515. //
  1516. // This program is distributed in the hope that it will be useful, but WITHOUT
  1517. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  1518. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  1519. // more details.
  1520. //
  1521. // You should have received a copy of the GNU General Public License along with
  1522. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  1523. // Place, Suite 330, Boston, MA 02111-1307 USA
  1524. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  1525. // These macros and constants can be used across the whole codebase.
  1526. // Unlike the values in user-settings.cgh, end users shouldn't modify these.
  1527. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  1528. //#include "../user-settings.h"
  1529. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  1530. #ifndef USER_SETTINGS_H
  1531. #define USER_SETTINGS_H
  1532. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  1533. // The Cg compiler uses different "profiles" with different capabilities.
  1534. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  1535. // require higher profiles like fp30 or fp40. The shader can't detect profile
  1536. // or driver capabilities, so instead you must comment or uncomment the lines
  1537. // below with "//" before "#define." Disable an option if you get compilation
  1538. // errors resembling those listed. Generally speaking, all of these options
  1539. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  1540. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  1541. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  1542. // Among other things, derivatives help us fix anisotropic filtering artifacts
  1543. // with curved manually tiled phosphor mask coords. Related errors:
  1544. // error C3004: function "float2 ddx(float2);" not supported in this profile
  1545. // error C3004: function "float2 ddy(float2);" not supported in this profile
  1546. //#define DRIVERS_ALLOW_DERIVATIVES
  1547. // Fine derivatives: Unsupported on older ATI cards.
  1548. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  1549. // fast single-pass blur operations. If your card uses coarse derivatives and
  1550. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  1551. #ifdef DRIVERS_ALLOW_DERIVATIVES
  1552. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  1553. #endif
  1554. // Dynamic looping: Requires an fp30 or newer profile.
  1555. // This makes phosphor mask resampling faster in some cases. Related errors:
  1556. // error C5013: profile does not support "for" statements and "for" could not
  1557. // be unrolled
  1558. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  1559. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  1560. // Using one static loop avoids overhead if the user is right, but if the user
  1561. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  1562. // binary search can potentially save some iterations. However, it may fail:
  1563. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  1564. // needed to compile program
  1565. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  1566. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  1567. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  1568. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  1569. // this profile
  1570. //#define DRIVERS_ALLOW_TEX2DLOD
  1571. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  1572. // artifacts from anisotropic filtering and mipmapping. Related errors:
  1573. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  1574. // in this profile
  1575. //#define DRIVERS_ALLOW_TEX2DBIAS
  1576. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  1577. // impose stricter limitations on register counts and instructions. Enable
  1578. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  1579. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  1580. // to compile program.
  1581. // Enabling integrated graphics compatibility mode will automatically disable:
  1582. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  1583. // (This may be reenabled in a later release.)
  1584. // 2.) RUNTIME_GEOMETRY_MODE
  1585. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  1586. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  1587. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  1588. // To disable a #define option, turn its line into a comment with "//."
  1589. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  1590. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  1591. // many of the options in this file and allow real-time tuning, but many of
  1592. // them are slower. Disabling them and using this text file will boost FPS.
  1593. #define RUNTIME_SHADER_PARAMS_ENABLE
  1594. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  1595. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  1596. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  1597. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  1598. #define RUNTIME_ANTIALIAS_WEIGHTS
  1599. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  1600. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1601. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  1602. // parameters? This will require more math or dynamic branching.
  1603. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  1604. // Specify the tilt at runtime? This makes things about 3% slower.
  1605. #define RUNTIME_GEOMETRY_TILT
  1606. // Specify the geometry mode at runtime?
  1607. #define RUNTIME_GEOMETRY_MODE
  1608. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  1609. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  1610. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  1611. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1612. // PHOSPHOR MASK:
  1613. // Manually resize the phosphor mask for best results (slower)? Disabling this
  1614. // removes the option to do so, but it may be faster without dynamic branches.
  1615. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  1616. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  1617. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  1618. // Larger blurs are expensive, but we need them to blur larger triads. We can
  1619. // detect the right blur if the triad size is static or our profile allows
  1620. // dynamic branches, but otherwise we use the largest blur the user indicates
  1621. // they might need:
  1622. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  1623. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  1624. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  1625. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  1626. // Here's a helpful chart:
  1627. // MaxTriadSize BlurSize MinTriadCountsByResolution
  1628. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1629. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1630. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1631. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1632. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1633. /////////////////////////////// USER PARAMETERS //////////////////////////////
  1634. // Note: Many of these static parameters are overridden by runtime shader
  1635. // parameters when those are enabled. However, many others are static codepath
  1636. // options that were cleaner or more convert to code as static constants.
  1637. // GAMMA:
  1638. static const float crt_gamma_static = 2.5; // range [1, 5]
  1639. static const float lcd_gamma_static = 2.2; // range [1, 5]
  1640. // LEVELS MANAGEMENT:
  1641. // Control the final multiplicative image contrast:
  1642. static const float levels_contrast_static = 1.0; // range [0, 4)
  1643. // We auto-dim to avoid clipping between passes and restore brightness
  1644. // later. Control the dim factor here: Lower values clip less but crush
  1645. // blacks more (static only for now).
  1646. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  1647. // HALATION/DIFFUSION/BLOOM:
  1648. // Halation weight: How much energy should be lost to electrons bounding
  1649. // around under the CRT glass and exciting random phosphors?
  1650. static const float halation_weight_static = 0.0; // range [0, 1]
  1651. // Refractive diffusion weight: How much light should spread/diffuse from
  1652. // refracting through the CRT glass?
  1653. static const float diffusion_weight_static = 0.075; // range [0, 1]
  1654. // Underestimate brightness: Bright areas bloom more, but we can base the
  1655. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  1656. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  1657. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  1658. // Blur all colors more than necessary for a softer phosphor bloom?
  1659. static const float bloom_excess_static = 0.0; // range [0, 1]
  1660. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  1661. // blurred resize of the input (convergence offsets are applied as well).
  1662. // There are three filter options (static option only for now):
  1663. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  1664. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  1665. // and beam_max_sigma is low.
  1666. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  1667. // always uses a static sigma regardless of beam_max_sigma or
  1668. // mask_num_triads_desired.
  1669. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  1670. // These options are more pronounced for the fast, unbloomed shader version.
  1671. #ifndef RADEON_FIX
  1672. static const float bloom_approx_filter_static = 2.0;
  1673. #else
  1674. static const float bloom_approx_filter_static = 1.0;
  1675. #endif
  1676. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  1677. // How many scanlines should contribute light to each pixel? Using more
  1678. // scanlines is slower (especially for a generalized Gaussian) but less
  1679. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  1680. // max_beam_sigma at which the closest unused weight is guaranteed <
  1681. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  1682. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  1683. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  1684. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  1685. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  1686. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  1687. static const float beam_num_scanlines = 3.0; // range [2, 6]
  1688. // A generalized Gaussian beam varies shape with color too, now just width.
  1689. // It's slower but more flexible (static option only for now).
  1690. static const bool beam_generalized_gaussian = true;
  1691. // What kind of scanline antialiasing do you want?
  1692. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  1693. // Integrals are slow (especially for generalized Gaussians) and rarely any
  1694. // better than 3x antialiasing (static option only for now).
  1695. static const float beam_antialias_level = 1.0; // range [0, 2]
  1696. // Min/max standard deviations for scanline beams: Higher values widen and
  1697. // soften scanlines. Depending on other options, low min sigmas can alias.
  1698. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  1699. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  1700. // Beam width varies as a function of color: A power function (0) is more
  1701. // configurable, but a spherical function (1) gives the widest beam
  1702. // variability without aliasing (static option only for now).
  1703. static const float beam_spot_shape_function = 0.0;
  1704. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  1705. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  1706. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  1707. // Generalized Gaussian max shape parameters: Higher values give flatter
  1708. // scanline plateaus and steeper dropoffs, simultaneously widening and
  1709. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  1710. // values > ~40.0 cause artifacts with integrals.
  1711. static const float beam_min_shape_static = 2.0; // range [2, 32]
  1712. static const float beam_max_shape_static = 4.0; // range [2, 32]
  1713. // Generalized Gaussian shape power: Affects how quickly the distribution
  1714. // changes shape from Gaussian to steep/plateaued as color increases from 0
  1715. // to 1.0. Higher powers appear softer for most colors, and lower powers
  1716. // appear sharper for most colors.
  1717. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  1718. // What filter should be used to sample scanlines horizontally?
  1719. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  1720. static const float beam_horiz_filter_static = 0.0;
  1721. // Standard deviation for horizontal Gaussian resampling:
  1722. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  1723. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  1724. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  1725. // limiting circuitry in some CRT's), or a weighted avg.?
  1726. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  1727. // Simulate scanline misconvergence? This needs 3x horizontal texture
  1728. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  1729. // later passes (static option only for now).
  1730. static const bool beam_misconvergence = true;
  1731. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  1732. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  1733. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  1734. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  1735. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  1736. // Detect interlacing (static option only for now)?
  1737. static const bool interlace_detect = true;
  1738. // Assume 1080-line sources are interlaced?
  1739. static const bool interlace_1080i_static = false;
  1740. // For interlaced sources, assume TFF (top-field first) or BFF order?
  1741. // (Whether this matters depends on the nature of the interlaced input.)
  1742. static const bool interlace_bff_static = false;
  1743. // ANTIALIASING:
  1744. // What AA level do you want for curvature/overscan/subpixels? Options:
  1745. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  1746. // (Static option only for now)
  1747. static const float aa_level = 12.0; // range [0, 24]
  1748. // What antialiasing filter do you want (static option only)? Options:
  1749. // 0: Box (separable), 1: Box (cylindrical),
  1750. // 2: Tent (separable), 3: Tent (cylindrical),
  1751. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  1752. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  1753. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  1754. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  1755. static const float aa_filter = 6.0; // range [0, 9]
  1756. // Flip the sample grid on odd/even frames (static option only for now)?
  1757. static const bool aa_temporal = false;
  1758. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  1759. // the blue offset is the negative r offset; range [0, 0.5]
  1760. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  1761. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  1762. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  1763. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  1764. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  1765. // 4.) C = 0.0 is a soft spline filter.
  1766. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  1767. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  1768. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  1769. // PHOSPHOR MASK:
  1770. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  1771. static const float mask_type_static = 1.0; // range [0, 2]
  1772. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  1773. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  1774. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  1775. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  1776. // is halfway decent with LUT mipmapping but atrocious without it.
  1777. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  1778. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  1779. // This mode reuses the same masks, so triads will be enormous unless
  1780. // you change the mask LUT filenames in your .cgp file.
  1781. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  1782. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  1783. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  1784. // will always be used to calculate the full bloom sigma statically.
  1785. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  1786. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  1787. // triads) will be rounded to the nearest integer tile size and clamped to
  1788. // obey minimum size constraints (imposed to reduce downsize taps) and
  1789. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  1790. // To increase the size limit, double the viewport-relative scales for the
  1791. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  1792. // range [1, mask_texture_small_size/mask_triads_per_tile]
  1793. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  1794. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  1795. // final size will be rounded and constrained as above); default 480.0
  1796. static const float mask_num_triads_desired_static = 480.0;
  1797. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  1798. // more samples and avoid moire a bit better, but some is unavoidable
  1799. // depending on the destination size (static option for now).
  1800. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  1801. // The mask is resized using a variable number of taps in each dimension,
  1802. // but some Cg profiles always fetch a constant number of taps no matter
  1803. // what (no dynamic branching). We can limit the maximum number of taps if
  1804. // we statically limit the minimum phosphor triad size. Larger values are
  1805. // faster, but the limit IS enforced (static option only, forever);
  1806. // range [1, mask_texture_small_size/mask_triads_per_tile]
  1807. // TODO: Make this 1.0 and compensate with smarter sampling!
  1808. static const float mask_min_allowed_triad_size = 2.0;
  1809. // GEOMETRY:
  1810. // Geometry mode:
  1811. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  1812. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  1813. static const float geom_mode_static = 0.0; // range [0, 3]
  1814. // Radius of curvature: Measured in units of your viewport's diagonal size.
  1815. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  1816. // View dist is the distance from the player to their physical screen, in
  1817. // units of the viewport's diagonal size. It controls the field of view.
  1818. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  1819. // Tilt angle in radians (clockwise around up and right vectors):
  1820. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  1821. // Aspect ratio: When the true viewport size is unknown, this value is used
  1822. // to help convert between the phosphor triad size and count, along with
  1823. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  1824. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  1825. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  1826. // default (256/224)*(54/47) = 1.313069909 (see below)
  1827. static const float geom_aspect_ratio_static = 1.313069909;
  1828. // Before getting into overscan, here's some general aspect ratio info:
  1829. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  1830. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  1831. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  1832. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  1833. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  1834. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  1835. // a.) Enable Retroarch's "Crop Overscan"
  1836. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  1837. // Real consoles use horizontal black padding in the signal, but emulators
  1838. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  1839. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  1840. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  1841. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  1842. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  1843. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  1844. // without doing a. or b., but horizontal image borders will be tighter
  1845. // than vertical ones, messing up curvature and overscan. Fixing the
  1846. // padding first corrects this.
  1847. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  1848. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  1849. // above: Values < 1.0 zoom out; range (0, inf)
  1850. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  1851. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  1852. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  1853. // with strong curvature (static option only for now).
  1854. static const bool geom_force_correct_tangent_matrix = true;
  1855. // BORDERS:
  1856. // Rounded border size in texture uv coords:
  1857. static const float border_size_static = 0.015; // range [0, 0.5]
  1858. // Border darkness: Moderate values darken the border smoothly, and high
  1859. // values make the image very dark just inside the border:
  1860. static const float border_darkness_static = 2.0; // range [0, inf)
  1861. // Border compression: High numbers compress border transitions, narrowing
  1862. // the dark border area.
  1863. static const float border_compress_static = 2.5; // range [1, inf)
  1864. #endif // USER_SETTINGS_H
  1865. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  1866. //#include "user-cgp-constants.h"
  1867. ///////////////////////// BEGIN USER-CGP-CONSTANTS /////////////////////////
  1868. #ifndef USER_CGP_CONSTANTS_H
  1869. #define USER_CGP_CONSTANTS_H
  1870. // IMPORTANT:
  1871. // These constants MUST be set appropriately for the settings in crt-royale.cgp
  1872. // (or whatever related .cgp file you're using). If they aren't, you're likely
  1873. // to get artifacts, the wrong phosphor mask size, etc. I wish these could be
  1874. // set directly in the .cgp file to make things easier, but...they can't.
  1875. // PASS SCALES AND RELATED CONSTANTS:
  1876. // Copy the absolute scale_x for BLOOM_APPROX. There are two major versions of
  1877. // this shader: One does a viewport-scale bloom, and the other skips it. The
  1878. // latter benefits from a higher bloom_approx_scale_x, so save both separately:
  1879. static const float bloom_approx_size_x = 320.0;
  1880. static const float bloom_approx_size_x_for_fake = 400.0;
  1881. // Copy the viewport-relative scales of the phosphor mask resize passes
  1882. // (MASK_RESIZE and the pass immediately preceding it):
  1883. static const float2 mask_resize_viewport_scale = float2(0.0625, 0.0625);
  1884. // Copy the geom_max_aspect_ratio used to calculate the MASK_RESIZE scales, etc.:
  1885. static const float geom_max_aspect_ratio = 4.0/3.0;
  1886. // PHOSPHOR MASK TEXTURE CONSTANTS:
  1887. // Set the following constants to reflect the properties of the phosphor mask
  1888. // texture named in crt-royale.cgp. The shader optionally resizes a mask tile
  1889. // based on user settings, then repeats a single tile until filling the screen.
  1890. // The shader must know the input texture size (default 64x64), and to manually
  1891. // resize, it must also know the horizontal triads per tile (default 8).
  1892. static const float2 mask_texture_small_size = float2(64.0, 64.0);
  1893. static const float2 mask_texture_large_size = float2(512.0, 512.0);
  1894. static const float mask_triads_per_tile = 8.0;
  1895. // We need the average brightness of the phosphor mask to compensate for the
  1896. // dimming it causes. The following four values are roughly correct for the
  1897. // masks included with the shader. Update the value for any LUT texture you
  1898. // change. [Un]comment "#define PHOSPHOR_MASK_GRILLE14" depending on whether
  1899. // the loaded aperture grille uses 14-pixel or 15-pixel stripes (default 15).
  1900. //#define PHOSPHOR_MASK_GRILLE14
  1901. static const float mask_grille14_avg_color = 50.6666666/255.0;
  1902. // TileableLinearApertureGrille14Wide7d33Spacing*.png
  1903. // TileableLinearApertureGrille14Wide10And6Spacing*.png
  1904. static const float mask_grille15_avg_color = 53.0/255.0;
  1905. // TileableLinearApertureGrille15Wide6d33Spacing*.png
  1906. // TileableLinearApertureGrille15Wide8And5d5Spacing*.png
  1907. static const float mask_slot_avg_color = 46.0/255.0;
  1908. // TileableLinearSlotMask15Wide9And4d5Horizontal8VerticalSpacing*.png
  1909. // TileableLinearSlotMaskTall15Wide9And4d5Horizontal9d14VerticalSpacing*.png
  1910. static const float mask_shadow_avg_color = 41.0/255.0;
  1911. // TileableLinearShadowMask*.png
  1912. // TileableLinearShadowMaskEDP*.png
  1913. #ifdef PHOSPHOR_MASK_GRILLE14
  1914. static const float mask_grille_avg_color = mask_grille14_avg_color;
  1915. #else
  1916. static const float mask_grille_avg_color = mask_grille15_avg_color;
  1917. #endif
  1918. #endif // USER_CGP_CONSTANTS_H
  1919. ////////////////////////// END USER-CGP-CONSTANTS //////////////////////////
  1920. //////////////////////////////// END INCLUDES ////////////////////////////////
  1921. /////////////////////////////// FIXED SETTINGS ///////////////////////////////
  1922. // Avoid dividing by zero; using a macro overloads for float, float2, etc.:
  1923. #define FIX_ZERO(c) (max(abs(c), 0.0000152587890625)) // 2^-16
  1924. // Ensure the first pass decodes CRT gamma and the last encodes LCD gamma.
  1925. #ifndef SIMULATE_CRT_ON_LCD
  1926. #define SIMULATE_CRT_ON_LCD
  1927. #endif
  1928. // Manually tiling a manually resized texture creates texture coord derivative
  1929. // discontinuities and confuses anisotropic filtering, causing discolored tile
  1930. // seams in the phosphor mask. Workarounds:
  1931. // a.) Using tex2Dlod disables anisotropic filtering for tiled masks. It's
  1932. // downgraded to tex2Dbias without DRIVERS_ALLOW_TEX2DLOD #defined and
  1933. // disabled without DRIVERS_ALLOW_TEX2DBIAS #defined either.
  1934. // b.) "Tile flat twice" requires drawing two full tiles without border padding
  1935. // to the resized mask FBO, and it's incompatible with same-pass curvature.
  1936. // (Same-pass curvature isn't used but could be in the future...maybe.)
  1937. // c.) "Fix discontinuities" requires derivatives and drawing one tile with
  1938. // border padding to the resized mask FBO, but it works with same-pass
  1939. // curvature. It's disabled without DRIVERS_ALLOW_DERIVATIVES #defined.
  1940. // Precedence: a, then, b, then c (if multiple strategies are #defined).
  1941. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD // 129.7 FPS, 4x, flat; 101.8 at fullscreen
  1942. #define ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE // 128.1 FPS, 4x, flat; 101.5 at fullscreen
  1943. #define ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES // 124.4 FPS, 4x, flat; 97.4 at fullscreen
  1944. // Also, manually resampling the phosphor mask is slightly blurrier with
  1945. // anisotropic filtering. (Resampling with mipmapping is even worse: It
  1946. // creates artifacts, but only with the fully bloomed shader.) The difference
  1947. // is subtle with small triads, but you can fix it for a small cost.
  1948. //#define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1949. ////////////////////////////// DERIVED SETTINGS //////////////////////////////
  1950. // Intel HD 4000 GPU's can't handle manual mask resizing (for now), setting the
  1951. // geometry mode at runtime, or a 4x4 true Gaussian resize. Disable
  1952. // incompatible settings ASAP. (INTEGRATED_GRAPHICS_COMPATIBILITY_MODE may be
  1953. // #defined by either user-settings.h or a wrapper .cg that #includes the
  1954. // current .cg pass.)
  1955. #ifdef INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  1956. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  1957. #undef PHOSPHOR_MASK_MANUALLY_RESIZE
  1958. #endif
  1959. #ifdef RUNTIME_GEOMETRY_MODE
  1960. #undef RUNTIME_GEOMETRY_MODE
  1961. #endif
  1962. // Mode 2 (4x4 Gaussian resize) won't work, and mode 1 (3x3 blur) is
  1963. // inferior in most cases, so replace 2.0 with 0.0:
  1964. static const float bloom_approx_filter =
  1965. bloom_approx_filter_static > 1.5 ? 0.0 : bloom_approx_filter_static;
  1966. #else
  1967. static const float bloom_approx_filter = bloom_approx_filter_static;
  1968. #endif
  1969. // Disable slow runtime paths if static parameters are used. Most of these
  1970. // won't be a problem anyway once the params are disabled, but some will.
  1971. #ifndef RUNTIME_SHADER_PARAMS_ENABLE
  1972. #ifdef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  1973. #undef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  1974. #endif
  1975. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  1976. #undef RUNTIME_ANTIALIAS_WEIGHTS
  1977. #endif
  1978. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1979. #undef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1980. #endif
  1981. #ifdef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  1982. #undef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  1983. #endif
  1984. #ifdef RUNTIME_GEOMETRY_TILT
  1985. #undef RUNTIME_GEOMETRY_TILT
  1986. #endif
  1987. #ifdef RUNTIME_GEOMETRY_MODE
  1988. #undef RUNTIME_GEOMETRY_MODE
  1989. #endif
  1990. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1991. #undef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1992. #endif
  1993. #endif
  1994. // Make tex2Dbias a backup for tex2Dlod for wider compatibility.
  1995. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  1996. #define ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1997. #endif
  1998. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1999. #define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2000. #endif
  2001. // Rule out unavailable anisotropic compatibility strategies:
  2002. #ifndef DRIVERS_ALLOW_DERIVATIVES
  2003. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2004. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2005. #endif
  2006. #endif
  2007. #ifndef DRIVERS_ALLOW_TEX2DLOD
  2008. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2009. #undef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2010. #endif
  2011. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2012. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2013. #endif
  2014. #ifdef ANTIALIAS_DISABLE_ANISOTROPIC
  2015. #undef ANTIALIAS_DISABLE_ANISOTROPIC
  2016. #endif
  2017. #endif
  2018. #ifndef DRIVERS_ALLOW_TEX2DBIAS
  2019. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2020. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2021. #endif
  2022. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2023. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2024. #endif
  2025. #endif
  2026. // Prioritize anisotropic tiling compatibility strategies by performance and
  2027. // disable unused strategies. This concentrates all the nesting in one place.
  2028. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2029. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2030. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2031. #endif
  2032. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2033. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2034. #endif
  2035. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2036. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2037. #endif
  2038. #else
  2039. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2040. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2041. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2042. #endif
  2043. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2044. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2045. #endif
  2046. #else
  2047. // ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE is only compatible with
  2048. // flat texture coords in the same pass, but that's all we use.
  2049. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2050. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2051. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2052. #endif
  2053. #endif
  2054. #endif
  2055. #endif
  2056. // The tex2Dlod and tex2Dbias strategies share a lot in common, and we can
  2057. // reduce some #ifdef nesting in the next section by essentially OR'ing them:
  2058. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2059. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2060. #endif
  2061. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2062. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2063. #endif
  2064. // Prioritize anisotropic resampling compatibility strategies the same way:
  2065. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2066. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2067. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2068. #endif
  2069. #endif
  2070. /////////////////////// DERIVED PHOSPHOR MASK CONSTANTS //////////////////////
  2071. // If we can use the large mipmapped LUT without mipmapping artifacts, we
  2072. // should: It gives us more options for using fewer samples.
  2073. #ifdef DRIVERS_ALLOW_TEX2DLOD
  2074. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2075. // TODO: Take advantage of this!
  2076. #define PHOSPHOR_MASK_RESIZE_MIPMAPPED_LUT
  2077. static const float2 mask_resize_src_lut_size = mask_texture_large_size;
  2078. #else
  2079. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  2080. #endif
  2081. #else
  2082. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  2083. #endif
  2084. // tex2D's sampler2D parameter MUST be a uniform global, a uniform input to
  2085. // main_fragment, or a static alias of one of the above. This makes it hard
  2086. // to select the phosphor mask at runtime: We can't even assign to a uniform
  2087. // global in the vertex shader or select a sampler2D in the vertex shader and
  2088. // pass it to the fragment shader (even with explicit TEXUNIT# bindings),
  2089. // because it just gives us the input texture or a black screen. However, we
  2090. // can get around these limitations by calling tex2D three times with different
  2091. // uniform samplers (or resizing the phosphor mask three times altogether).
  2092. // With dynamic branches, we can process only one of these branches on top of
  2093. // quickly discarding fragments we don't need (cgc seems able to overcome
  2094. // limigations around dependent texture fetches inside of branches). Without
  2095. // dynamic branches, we have to process every branch for every fragment...which
  2096. // is slower. Runtime sampling mode selection is slower without dynamic
  2097. // branches as well. Let the user's static #defines decide if it's worth it.
  2098. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  2099. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2100. #else
  2101. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2102. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2103. #endif
  2104. #endif
  2105. // We need to render some minimum number of tiles in the resize passes.
  2106. // We need at least 1.0 just to repeat a single tile, and we need extra
  2107. // padding beyond that for anisotropic filtering, discontinuitity fixing,
  2108. // antialiasing, same-pass curvature (not currently used), etc. First
  2109. // determine how many border texels and tiles we need, based on how the result
  2110. // will be sampled:
  2111. #ifdef GEOMETRY_EARLY
  2112. static const float max_subpixel_offset = aa_subpixel_r_offset_static.x;
  2113. // Most antialiasing filters have a base radius of 4.0 pixels:
  2114. static const float max_aa_base_pixel_border = 4.0 +
  2115. max_subpixel_offset;
  2116. #else
  2117. static const float max_aa_base_pixel_border = 0.0;
  2118. #endif
  2119. // Anisotropic filtering adds about 0.5 to the pixel border:
  2120. #ifndef ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2121. static const float max_aniso_pixel_border = max_aa_base_pixel_border + 0.5;
  2122. #else
  2123. static const float max_aniso_pixel_border = max_aa_base_pixel_border;
  2124. #endif
  2125. // Fixing discontinuities adds 1.0 more to the pixel border:
  2126. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2127. static const float max_tiled_pixel_border = max_aniso_pixel_border + 1.0;
  2128. #else
  2129. static const float max_tiled_pixel_border = max_aniso_pixel_border;
  2130. #endif
  2131. // Convert the pixel border to an integer texel border. Assume same-pass
  2132. // curvature about triples the texel frequency:
  2133. #ifdef GEOMETRY_EARLY
  2134. static const float max_mask_texel_border =
  2135. ceil(max_tiled_pixel_border * 3.0);
  2136. #else
  2137. static const float max_mask_texel_border = ceil(max_tiled_pixel_border);
  2138. #endif
  2139. // Convert the texel border to a tile border using worst-case assumptions:
  2140. static const float max_mask_tile_border = max_mask_texel_border/
  2141. (mask_min_allowed_triad_size * mask_triads_per_tile);
  2142. // Finally, set the number of resized tiles to render to MASK_RESIZE, and set
  2143. // the starting texel (inside borders) for sampling it.
  2144. #ifndef GEOMETRY_EARLY
  2145. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2146. // Special case: Render two tiles without borders. Anisotropic
  2147. // filtering doesn't seem to be a problem here.
  2148. static const float mask_resize_num_tiles = 1.0 + 1.0;
  2149. static const float mask_start_texels = 0.0;
  2150. #else
  2151. static const float mask_resize_num_tiles = 1.0 +
  2152. 2.0 * max_mask_tile_border;
  2153. static const float mask_start_texels = max_mask_texel_border;
  2154. #endif
  2155. #else
  2156. static const float mask_resize_num_tiles = 1.0 + 2.0*max_mask_tile_border;
  2157. static const float mask_start_texels = max_mask_texel_border;
  2158. #endif
  2159. // We have to fit mask_resize_num_tiles into an FBO with a viewport scale of
  2160. // mask_resize_viewport_scale. This limits the maximum final triad size.
  2161. // Estimate the minimum number of triads we can split the screen into in each
  2162. // dimension (we'll be as correct as mask_resize_viewport_scale is):
  2163. static const float mask_resize_num_triads =
  2164. mask_resize_num_tiles * mask_triads_per_tile;
  2165. static const float2 min_allowed_viewport_triads =
  2166. float2(mask_resize_num_triads) / mask_resize_viewport_scale;
  2167. //////////////////////// COMMON MATHEMATICAL CONSTANTS ///////////////////////
  2168. static const float pi = 3.141592653589;
  2169. // We often want to find the location of the previous texel, e.g.:
  2170. // const float2 curr_texel = uv * texture_size;
  2171. // const float2 prev_texel = floor(curr_texel - float2(0.5)) + float2(0.5);
  2172. // const float2 prev_texel_uv = prev_texel / texture_size;
  2173. // However, many GPU drivers round incorrectly around exact texel locations.
  2174. // We need to subtract a little less than 0.5 before flooring, and some GPU's
  2175. // require this value to be farther from 0.5 than others; define it here.
  2176. // const float2 prev_texel =
  2177. // floor(curr_texel - float2(under_half)) + float2(0.5);
  2178. static const float under_half = 0.4995;
  2179. #endif // DERIVED_SETTINGS_AND_CONSTANTS_H
  2180. //////////////////// END DERIVED-SETTINGS-AND-CONSTANTS /////////////////////
  2181. //////////////////////////////// END INCLUDES ////////////////////////////////
  2182. // Override some parameters for gamma-management.h and tex2Dantialias.h:
  2183. #define OVERRIDE_DEVICE_GAMMA
  2184. static const float gba_gamma = 3.5; // Irrelevant but necessary to define.
  2185. #define ANTIALIAS_OVERRIDE_BASICS
  2186. #define ANTIALIAS_OVERRIDE_PARAMETERS
  2187. // Provide accessors for vector constants that pack scalar uniforms:
  2188. inline float2 get_aspect_vector(const float geom_aspect_ratio)
  2189. {
  2190. // Get an aspect ratio vector. Enforce geom_max_aspect_ratio, and prevent
  2191. // the absolute scale from affecting the uv-mapping for curvature:
  2192. const float geom_clamped_aspect_ratio =
  2193. min(geom_aspect_ratio, geom_max_aspect_ratio);
  2194. const float2 geom_aspect =
  2195. normalize(float2(geom_clamped_aspect_ratio, 1.0));
  2196. return geom_aspect;
  2197. }
  2198. inline float2 get_geom_overscan_vector()
  2199. {
  2200. return float2(geom_overscan_x, geom_overscan_y);
  2201. }
  2202. inline float2 get_geom_tilt_angle_vector()
  2203. {
  2204. return float2(geom_tilt_angle_x, geom_tilt_angle_y);
  2205. }
  2206. inline float3 get_convergence_offsets_x_vector()
  2207. {
  2208. return float3(convergence_offset_x_r, convergence_offset_x_g,
  2209. convergence_offset_x_b);
  2210. }
  2211. inline float3 get_convergence_offsets_y_vector()
  2212. {
  2213. return float3(convergence_offset_y_r, convergence_offset_y_g,
  2214. convergence_offset_y_b);
  2215. }
  2216. inline float2 get_convergence_offsets_r_vector()
  2217. {
  2218. return float2(convergence_offset_x_r, convergence_offset_y_r);
  2219. }
  2220. inline float2 get_convergence_offsets_g_vector()
  2221. {
  2222. return float2(convergence_offset_x_g, convergence_offset_y_g);
  2223. }
  2224. inline float2 get_convergence_offsets_b_vector()
  2225. {
  2226. return float2(convergence_offset_x_b, convergence_offset_y_b);
  2227. }
  2228. inline float2 get_aa_subpixel_r_offset()
  2229. {
  2230. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  2231. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  2232. // WARNING: THIS IS EXTREMELY EXPENSIVE.
  2233. return float2(aa_subpixel_r_offset_x_runtime,
  2234. aa_subpixel_r_offset_y_runtime);
  2235. #else
  2236. return aa_subpixel_r_offset_static;
  2237. #endif
  2238. #else
  2239. return aa_subpixel_r_offset_static;
  2240. #endif
  2241. }
  2242. // Provide accessors settings which still need "cooking:"
  2243. inline float get_mask_amplify()
  2244. {
  2245. static const float mask_grille_amplify = 1.0/mask_grille_avg_color;
  2246. static const float mask_slot_amplify = 1.0/mask_slot_avg_color;
  2247. static const float mask_shadow_amplify = 1.0/mask_shadow_avg_color;
  2248. return mask_type < 0.5 ? mask_grille_amplify :
  2249. mask_type < 1.5 ? mask_slot_amplify :
  2250. mask_shadow_amplify;
  2251. }
  2252. inline float get_mask_sample_mode()
  2253. {
  2254. #ifdef RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2255. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  2256. return mask_sample_mode_desired;
  2257. #else
  2258. return clamp(mask_sample_mode_desired, 1.0, 2.0);
  2259. #endif
  2260. #else
  2261. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  2262. return mask_sample_mode_static;
  2263. #else
  2264. return clamp(mask_sample_mode_static, 1.0, 2.0);
  2265. #endif
  2266. #endif
  2267. }
  2268. #endif // BIND_SHADER_PARAMS_H
  2269. //////////////////////////// END BIND-SHADER-PARAMS ///////////////////////////
  2270. /////////////////////////////// VERTEX INCLUDES //////////////////////////////
  2271. //#include "../../../../include/gamma-management.h"
  2272. //////////////////////////// BEGIN GAMMA-MANAGEMENT //////////////////////////
  2273. #ifndef GAMMA_MANAGEMENT_H
  2274. #define GAMMA_MANAGEMENT_H
  2275. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  2276. // Copyright (C) 2014 TroggleMonkey
  2277. //
  2278. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2279. // of this software and associated documentation files (the "Software"), to
  2280. // deal in the Software without restriction, including without limitation the
  2281. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  2282. // sell copies of the Software, and to permit persons to whom the Software is
  2283. // furnished to do so, subject to the following conditions:
  2284. //
  2285. // The above copyright notice and this permission notice shall be included in
  2286. // all copies or substantial portions of the Software.
  2287. //
  2288. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2289. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2290. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2291. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2292. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  2293. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  2294. // IN THE SOFTWARE.
  2295. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  2296. // This file provides gamma-aware tex*D*() and encode_output() functions.
  2297. // Requires: Before #include-ing this file, the including file must #define
  2298. // the following macros when applicable and follow their rules:
  2299. // 1.) #define FIRST_PASS if this is the first pass.
  2300. // 2.) #define LAST_PASS if this is the last pass.
  2301. // 3.) If sRGB is available, set srgb_framebufferN = "true" for
  2302. // every pass except the last in your .cgp preset.
  2303. // 4.) If sRGB isn't available but you want gamma-correctness with
  2304. // no banding, #define GAMMA_ENCODE_EVERY_FBO each pass.
  2305. // 5.) #define SIMULATE_CRT_ON_LCD if desired (precedence over 5-7)
  2306. // 6.) #define SIMULATE_GBA_ON_LCD if desired (precedence over 6-7)
  2307. // 7.) #define SIMULATE_LCD_ON_CRT if desired (precedence over 7)
  2308. // 8.) #define SIMULATE_GBA_ON_CRT if desired (precedence over -)
  2309. // If an option in [5, 8] is #defined in the first or last pass, it
  2310. // should be #defined for both. It shouldn't make a difference
  2311. // whether it's #defined for intermediate passes or not.
  2312. // Optional: The including file (or an earlier included file) may optionally
  2313. // #define a number of macros indicating it will override certain
  2314. // macros and associated constants are as follows:
  2315. // static constants with either static or uniform constants. The
  2316. // 1.) OVERRIDE_STANDARD_GAMMA: The user must first define:
  2317. // static const float ntsc_gamma
  2318. // static const float pal_gamma
  2319. // static const float crt_reference_gamma_high
  2320. // static const float crt_reference_gamma_low
  2321. // static const float lcd_reference_gamma
  2322. // static const float crt_office_gamma
  2323. // static const float lcd_office_gamma
  2324. // 2.) OVERRIDE_DEVICE_GAMMA: The user must first define:
  2325. // static const float crt_gamma
  2326. // static const float gba_gamma
  2327. // static const float lcd_gamma
  2328. // 3.) OVERRIDE_FINAL_GAMMA: The user must first define:
  2329. // static const float input_gamma
  2330. // static const float intermediate_gamma
  2331. // static const float output_gamma
  2332. // (intermediate_gamma is for GAMMA_ENCODE_EVERY_FBO.)
  2333. // 4.) OVERRIDE_ALPHA_ASSUMPTIONS: The user must first define:
  2334. // static const bool assume_opaque_alpha
  2335. // The gamma constant overrides must be used in every pass or none,
  2336. // and OVERRIDE_FINAL_GAMMA bypasses all of the SIMULATE* macros.
  2337. // OVERRIDE_ALPHA_ASSUMPTIONS may be set on a per-pass basis.
  2338. // Usage: After setting macros appropriately, ignore gamma correction and
  2339. // replace all tex*D*() calls with equivalent gamma-aware
  2340. // tex*D*_linearize calls, except:
  2341. // 1.) When you read an LUT, use regular tex*D or a gamma-specified
  2342. // function, depending on its gamma encoding:
  2343. // tex*D*_linearize_gamma (takes a runtime gamma parameter)
  2344. // 2.) If you must read pass0's original input in a later pass, use
  2345. // tex2D_linearize_ntsc_gamma. If you want to read pass0's
  2346. // input with gamma-corrected bilinear filtering, consider
  2347. // creating a first linearizing pass and reading from the input
  2348. // of pass1 later.
  2349. // Then, return encode_output(color) from every fragment shader.
  2350. // Finally, use the global gamma_aware_bilinear boolean if you want
  2351. // to statically branch based on whether bilinear filtering is
  2352. // gamma-correct or not (e.g. for placing Gaussian blur samples).
  2353. //
  2354. // Detailed Policy:
  2355. // tex*D*_linearize() functions enforce a consistent gamma-management policy
  2356. // based on the FIRST_PASS and GAMMA_ENCODE_EVERY_FBO settings. They assume
  2357. // their input texture has the same encoding characteristics as the input for
  2358. // the current pass (which doesn't apply to the exceptions listed above).
  2359. // Similarly, encode_output() enforces a policy based on the LAST_PASS and
  2360. // GAMMA_ENCODE_EVERY_FBO settings. Together, they result in one of the
  2361. // following two pipelines.
  2362. // Typical pipeline with intermediate sRGB framebuffers:
  2363. // linear_color = pow(pass0_encoded_color, input_gamma);
  2364. // intermediate_output = linear_color; // Automatic sRGB encoding
  2365. // linear_color = intermediate_output; // Automatic sRGB decoding
  2366. // final_output = pow(intermediate_output, 1.0/output_gamma);
  2367. // Typical pipeline without intermediate sRGB framebuffers:
  2368. // linear_color = pow(pass0_encoded_color, input_gamma);
  2369. // intermediate_output = pow(linear_color, 1.0/intermediate_gamma);
  2370. // linear_color = pow(intermediate_output, intermediate_gamma);
  2371. // final_output = pow(intermediate_output, 1.0/output_gamma);
  2372. // Using GAMMA_ENCODE_EVERY_FBO is much slower, but it's provided as a way to
  2373. // easily get gamma-correctness without banding on devices where sRGB isn't
  2374. // supported.
  2375. //
  2376. // Use This Header to Maximize Code Reuse:
  2377. // The purpose of this header is to provide a consistent interface for texture
  2378. // reads and output gamma-encoding that localizes and abstracts away all the
  2379. // annoying details. This greatly reduces the amount of code in each shader
  2380. // pass that depends on the pass number in the .cgp preset or whether sRGB
  2381. // FBO's are being used: You can trivially change the gamma behavior of your
  2382. // whole pass by commenting or uncommenting 1-3 #defines. To reuse the same
  2383. // code in your first, Nth, and last passes, you can even put it all in another
  2384. // header file and #include it from skeleton .cg files that #define the
  2385. // appropriate pass-specific settings.
  2386. //
  2387. // Rationale for Using Three Macros:
  2388. // This file uses GAMMA_ENCODE_EVERY_FBO instead of an opposite macro like
  2389. // SRGB_PIPELINE to ensure sRGB is assumed by default, which hopefully imposes
  2390. // a lower maintenance burden on each pass. At first glance it seems we could
  2391. // accomplish everything with two macros: GAMMA_CORRECT_IN / GAMMA_CORRECT_OUT.
  2392. // This works for simple use cases where input_gamma == output_gamma, but it
  2393. // breaks down for more complex scenarios like CRT simulation, where the pass
  2394. // number determines the gamma encoding of the input and output.
  2395. /////////////////////////////// BASE CONSTANTS ///////////////////////////////
  2396. // Set standard gamma constants, but allow users to override them:
  2397. #ifndef OVERRIDE_STANDARD_GAMMA
  2398. // Standard encoding gammas:
  2399. static const float ntsc_gamma = 2.2; // Best to use NTSC for PAL too?
  2400. static const float pal_gamma = 2.8; // Never actually 2.8 in practice
  2401. // Typical device decoding gammas (only use for emulating devices):
  2402. // CRT/LCD reference gammas are higher than NTSC and Rec.709 video standard
  2403. // gammas: The standards purposely undercorrected for an analog CRT's
  2404. // assumed 2.5 reference display gamma to maintain contrast in assumed
  2405. // [dark] viewing conditions: http://www.poynton.com/PDFs/GammaFAQ.pdf
  2406. // These unstated assumptions about display gamma and perceptual rendering
  2407. // intent caused a lot of confusion, and more modern CRT's seemed to target
  2408. // NTSC 2.2 gamma with circuitry. LCD displays seem to have followed suit
  2409. // (they struggle near black with 2.5 gamma anyway), especially PC/laptop
  2410. // displays designed to view sRGB in bright environments. (Standards are
  2411. // also in flux again with BT.1886, but it's underspecified for displays.)
  2412. static const float crt_reference_gamma_high = 2.5; // In (2.35, 2.55)
  2413. static const float crt_reference_gamma_low = 2.35; // In (2.35, 2.55)
  2414. static const float lcd_reference_gamma = 2.5; // To match CRT
  2415. static const float crt_office_gamma = 2.2; // Circuitry-adjusted for NTSC
  2416. static const float lcd_office_gamma = 2.2; // Approximates sRGB
  2417. #endif // OVERRIDE_STANDARD_GAMMA
  2418. // Assuming alpha == 1.0 might make it easier for users to avoid some bugs,
  2419. // but only if they're aware of it.
  2420. #ifndef OVERRIDE_ALPHA_ASSUMPTIONS
  2421. static const bool assume_opaque_alpha = false;
  2422. #endif
  2423. /////////////////////// DERIVED CONSTANTS AS FUNCTIONS ///////////////////////
  2424. // gamma-management.h should be compatible with overriding gamma values with
  2425. // runtime user parameters, but we can only define other global constants in
  2426. // terms of static constants, not uniform user parameters. To get around this
  2427. // limitation, we need to define derived constants using functions.
  2428. // Set device gamma constants, but allow users to override them:
  2429. #ifdef OVERRIDE_DEVICE_GAMMA
  2430. // The user promises to globally define the appropriate constants:
  2431. inline float get_crt_gamma() { return crt_gamma; }
  2432. inline float get_gba_gamma() { return gba_gamma; }
  2433. inline float get_lcd_gamma() { return lcd_gamma; }
  2434. #else
  2435. inline float get_crt_gamma() { return crt_reference_gamma_high; }
  2436. inline float get_gba_gamma() { return 3.5; } // Game Boy Advance; in (3.0, 4.0)
  2437. inline float get_lcd_gamma() { return lcd_office_gamma; }
  2438. #endif // OVERRIDE_DEVICE_GAMMA
  2439. // Set decoding/encoding gammas for the first/lass passes, but allow overrides:
  2440. #ifdef OVERRIDE_FINAL_GAMMA
  2441. // The user promises to globally define the appropriate constants:
  2442. inline float get_intermediate_gamma() { return intermediate_gamma; }
  2443. inline float get_input_gamma() { return input_gamma; }
  2444. inline float get_output_gamma() { return output_gamma; }
  2445. #else
  2446. // If we gamma-correct every pass, always use ntsc_gamma between passes to
  2447. // ensure middle passes don't need to care if anything is being simulated:
  2448. inline float get_intermediate_gamma() { return ntsc_gamma; }
  2449. #ifdef SIMULATE_CRT_ON_LCD
  2450. inline float get_input_gamma() { return get_crt_gamma(); }
  2451. inline float get_output_gamma() { return get_lcd_gamma(); }
  2452. #else
  2453. #ifdef SIMULATE_GBA_ON_LCD
  2454. inline float get_input_gamma() { return get_gba_gamma(); }
  2455. inline float get_output_gamma() { return get_lcd_gamma(); }
  2456. #else
  2457. #ifdef SIMULATE_LCD_ON_CRT
  2458. inline float get_input_gamma() { return get_lcd_gamma(); }
  2459. inline float get_output_gamma() { return get_crt_gamma(); }
  2460. #else
  2461. #ifdef SIMULATE_GBA_ON_CRT
  2462. inline float get_input_gamma() { return get_gba_gamma(); }
  2463. inline float get_output_gamma() { return get_crt_gamma(); }
  2464. #else // Don't simulate anything:
  2465. inline float get_input_gamma() { return ntsc_gamma; }
  2466. inline float get_output_gamma() { return ntsc_gamma; }
  2467. #endif // SIMULATE_GBA_ON_CRT
  2468. #endif // SIMULATE_LCD_ON_CRT
  2469. #endif // SIMULATE_GBA_ON_LCD
  2470. #endif // SIMULATE_CRT_ON_LCD
  2471. #endif // OVERRIDE_FINAL_GAMMA
  2472. // Set decoding/encoding gammas for the current pass. Use static constants for
  2473. // linearize_input and gamma_encode_output, because they aren't derived, and
  2474. // they let the compiler do dead-code elimination.
  2475. #ifndef GAMMA_ENCODE_EVERY_FBO
  2476. #ifdef FIRST_PASS
  2477. static const bool linearize_input = true;
  2478. inline float get_pass_input_gamma() { return get_input_gamma(); }
  2479. #else
  2480. static const bool linearize_input = false;
  2481. inline float get_pass_input_gamma() { return 1.0; }
  2482. #endif
  2483. #ifdef LAST_PASS
  2484. static const bool gamma_encode_output = true;
  2485. inline float get_pass_output_gamma() { return get_output_gamma(); }
  2486. #else
  2487. static const bool gamma_encode_output = false;
  2488. inline float get_pass_output_gamma() { return 1.0; }
  2489. #endif
  2490. #else
  2491. static const bool linearize_input = true;
  2492. static const bool gamma_encode_output = true;
  2493. #ifdef FIRST_PASS
  2494. inline float get_pass_input_gamma() { return get_input_gamma(); }
  2495. #else
  2496. inline float get_pass_input_gamma() { return get_intermediate_gamma(); }
  2497. #endif
  2498. #ifdef LAST_PASS
  2499. inline float get_pass_output_gamma() { return get_output_gamma(); }
  2500. #else
  2501. inline float get_pass_output_gamma() { return get_intermediate_gamma(); }
  2502. #endif
  2503. #endif
  2504. // Users might want to know if bilinear filtering will be gamma-correct:
  2505. static const bool gamma_aware_bilinear = !linearize_input;
  2506. ////////////////////// COLOR ENCODING/DECODING FUNCTIONS /////////////////////
  2507. inline float4 encode_output(const float4 color)
  2508. {
  2509. if(gamma_encode_output)
  2510. {
  2511. if(assume_opaque_alpha)
  2512. {
  2513. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), 1.0);
  2514. }
  2515. else
  2516. {
  2517. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), color.a);
  2518. }
  2519. }
  2520. else
  2521. {
  2522. return color;
  2523. }
  2524. }
  2525. inline float4 decode_input(const float4 color)
  2526. {
  2527. if(linearize_input)
  2528. {
  2529. if(assume_opaque_alpha)
  2530. {
  2531. return float4(pow(color.rgb, float3(get_pass_input_gamma())), 1.0);
  2532. }
  2533. else
  2534. {
  2535. return float4(pow(color.rgb, float3(get_pass_input_gamma())), color.a);
  2536. }
  2537. }
  2538. else
  2539. {
  2540. return color;
  2541. }
  2542. }
  2543. inline float4 decode_gamma_input(const float4 color, const float3 gamma)
  2544. {
  2545. if(assume_opaque_alpha)
  2546. {
  2547. return float4(pow(color.rgb, gamma), 1.0);
  2548. }
  2549. else
  2550. {
  2551. return float4(pow(color.rgb, gamma), color.a);
  2552. }
  2553. }
  2554. //TODO/FIXME: I have no idea why replacing the lookup wrappers with this macro fixes the blurs being offset ¯\_(ツ)_/¯
  2555. //#define tex2D_linearize(C, D) decode_input(vec4(COMPAT_TEXTURE(C, D)))
  2556. // EDIT: it's the 'const' in front of the coords that's doing it
  2557. /////////////////////////// TEXTURE LOOKUP WRAPPERS //////////////////////////
  2558. // "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  2559. // Provide a wide array of linearizing texture lookup wrapper functions. The
  2560. // Cg shader spec Retroarch uses only allows for 2D textures, but 1D and 3D
  2561. // lookups are provided for completeness in case that changes someday. Nobody
  2562. // is likely to use the *fetch and *proj functions, but they're included just
  2563. // in case. The only tex*D texture sampling functions omitted are:
  2564. // - tex*Dcmpbias
  2565. // - tex*Dcmplod
  2566. // - tex*DARRAY*
  2567. // - tex*DMS*
  2568. // - Variants returning integers
  2569. // Standard line length restrictions are ignored below for vertical brevity.
  2570. /*
  2571. // tex1D:
  2572. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords)
  2573. { return decode_input(tex1D(tex, tex_coords)); }
  2574. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords)
  2575. { return decode_input(tex1D(tex, tex_coords)); }
  2576. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const int texel_off)
  2577. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  2578. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  2579. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  2580. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy)
  2581. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  2582. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy)
  2583. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  2584. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy, const int texel_off)
  2585. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  2586. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy, const int texel_off)
  2587. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  2588. // tex1Dbias:
  2589. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords)
  2590. { return decode_input(tex1Dbias(tex, tex_coords)); }
  2591. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  2592. { return decode_input(tex1Dbias(tex, tex_coords, texel_off)); }
  2593. // tex1Dfetch:
  2594. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords)
  2595. { return decode_input(tex1Dfetch(tex, tex_coords)); }
  2596. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords, const int texel_off)
  2597. { return decode_input(tex1Dfetch(tex, tex_coords, texel_off)); }
  2598. // tex1Dlod:
  2599. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords)
  2600. { return decode_input(tex1Dlod(tex, tex_coords)); }
  2601. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  2602. { return decode_input(tex1Dlod(tex, tex_coords, texel_off)); }
  2603. // tex1Dproj:
  2604. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords)
  2605. { return decode_input(tex1Dproj(tex, tex_coords)); }
  2606. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords)
  2607. { return decode_input(tex1Dproj(tex, tex_coords)); }
  2608. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  2609. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  2610. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords, const int texel_off)
  2611. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  2612. */
  2613. // tex2D:
  2614. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords)
  2615. { return decode_input(COMPAT_TEXTURE(tex, tex_coords)); }
  2616. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords)
  2617. { return decode_input(COMPAT_TEXTURE(tex, tex_coords.xy)); }
  2618. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords, int texel_off)
  2619. { return decode_input(textureLod(tex, tex_coords, texel_off)); }
  2620. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords, int texel_off)
  2621. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  2622. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy)
  2623. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  2624. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy)
  2625. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  2626. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  2627. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  2628. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  2629. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  2630. // tex2Dbias:
  2631. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords)
  2632. //{ return decode_input(tex2Dbias(tex, tex_coords)); }
  2633. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  2634. //{ return decode_input(tex2Dbias(tex, tex_coords, texel_off)); }
  2635. // tex2Dfetch:
  2636. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords)
  2637. //{ return decode_input(tex2Dfetch(tex, tex_coords)); }
  2638. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords, const int texel_off)
  2639. //{ return decode_input(tex2Dfetch(tex, tex_coords, texel_off)); }
  2640. // tex2Dlod:
  2641. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords)
  2642. { return decode_input(textureLod(tex, tex_coords.xy, 0.0)); }
  2643. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords, int texel_off)
  2644. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  2645. /*
  2646. // tex2Dproj:
  2647. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords)
  2648. { return decode_input(tex2Dproj(tex, tex_coords)); }
  2649. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords)
  2650. { return decode_input(tex2Dproj(tex, tex_coords)); }
  2651. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords, const int texel_off)
  2652. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  2653. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  2654. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  2655. */
  2656. /*
  2657. // tex3D:
  2658. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords)
  2659. { return decode_input(tex3D(tex, tex_coords)); }
  2660. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const int texel_off)
  2661. { return decode_input(tex3D(tex, tex_coords, texel_off)); }
  2662. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy)
  2663. { return decode_input(tex3D(tex, tex_coords, dx, dy)); }
  2664. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy, const int texel_off)
  2665. { return decode_input(tex3D(tex, tex_coords, dx, dy, texel_off)); }
  2666. // tex3Dbias:
  2667. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords)
  2668. { return decode_input(tex3Dbias(tex, tex_coords)); }
  2669. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  2670. { return decode_input(tex3Dbias(tex, tex_coords, texel_off)); }
  2671. // tex3Dfetch:
  2672. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords)
  2673. { return decode_input(tex3Dfetch(tex, tex_coords)); }
  2674. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords, const int texel_off)
  2675. { return decode_input(tex3Dfetch(tex, tex_coords, texel_off)); }
  2676. // tex3Dlod:
  2677. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords)
  2678. { return decode_input(tex3Dlod(tex, tex_coords)); }
  2679. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  2680. { return decode_input(tex3Dlod(tex, tex_coords, texel_off)); }
  2681. // tex3Dproj:
  2682. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords)
  2683. { return decode_input(tex3Dproj(tex, tex_coords)); }
  2684. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  2685. { return decode_input(tex3Dproj(tex, tex_coords, texel_off)); }
  2686. /////////*
  2687. // NONSTANDARD "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  2688. // This narrow selection of nonstandard tex2D* functions can be useful:
  2689. // tex2Dlod0: Automatically fill in the tex2D LOD parameter for mip level 0.
  2690. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords)
  2691. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0))); }
  2692. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords, const int texel_off)
  2693. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0), texel_off)); }
  2694. // MANUALLY LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  2695. // Provide a narrower selection of tex2D* wrapper functions that decode an
  2696. // input sample with a specified gamma value. These are useful for reading
  2697. // LUT's and for reading the input of pass0 in a later pass.
  2698. // tex2D:
  2699. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float3 gamma)
  2700. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords), gamma); }
  2701. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float3 gamma)
  2702. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords.xy), gamma); }
  2703. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const int texel_off, const float3 gamma)
  2704. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  2705. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const int texel_off, const float3 gamma)
  2706. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  2707. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  2708. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  2709. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  2710. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  2711. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  2712. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  2713. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  2714. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  2715. /*
  2716. // tex2Dbias:
  2717. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const float3 gamma)
  2718. { return decode_gamma_input(tex2Dbias(tex, tex_coords), gamma); }
  2719. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const int texel_off, const float3 gamma)
  2720. { return decode_gamma_input(tex2Dbias(tex, tex_coords, texel_off), gamma); }
  2721. // tex2Dfetch:
  2722. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const float3 gamma)
  2723. { return decode_gamma_input(tex2Dfetch(tex, tex_coords), gamma); }
  2724. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const int texel_off, const float3 gamma)
  2725. { return decode_gamma_input(tex2Dfetch(tex, tex_coords, texel_off), gamma); }
  2726. */
  2727. // tex2Dlod:
  2728. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, float3 gamma)
  2729. { return decode_gamma_input(textureLod(tex, tex_coords.xy, 0.0), gamma); }
  2730. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, int texel_off, float3 gamma)
  2731. { return decode_gamma_input(textureLod(tex, tex_coords.xy, texel_off), gamma); }
  2732. #endif // GAMMA_MANAGEMENT_H
  2733. //////////////////////////// END GAMMA-MANAGEMENT //////////////////////////
  2734. //#include "phosphor-mask-resizing.h"
  2735. //////////////////////// BEGIN PHOSPHOR-MASK-RESIZING ////////////////////////
  2736. #ifndef PHOSPHOR_MASK_RESIZING_H
  2737. #define PHOSPHOR_MASK_RESIZING_H
  2738. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  2739. // crt-royale: A full-featured CRT shader, with cheese.
  2740. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  2741. //
  2742. // This program is free software; you can redistribute it and/or modify it
  2743. // under the terms of the GNU General Public License as published by the Free
  2744. // Software Foundation; either version 2 of the License, or any later version.
  2745. //
  2746. // This program is distributed in the hope that it will be useful, but WITHOUT
  2747. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  2748. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  2749. // more details.
  2750. //
  2751. // You should have received a copy of the GNU General Public License along with
  2752. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  2753. // Place, Suite 330, Boston, MA 02111-1307 USA
  2754. ////////////////////////////////// INCLUDES //////////////////////////////////
  2755. //#include "../user-settings.h"
  2756. //#include "derived-settings-and-constants.h"
  2757. ///////////////////////////// CODEPATH SELECTION /////////////////////////////
  2758. // Choose a looping strategy based on what's allowed:
  2759. // Dynamic loops not allowed: Use a flat static loop.
  2760. // Dynamic loops accomodated: Coarsely branch around static loops.
  2761. // Dynamic loops assumed allowed: Use a flat dynamic loop.
  2762. #ifndef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  2763. #ifdef ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  2764. #define BREAK_LOOPS_INTO_PIECES
  2765. #else
  2766. #define USE_SINGLE_STATIC_LOOP
  2767. #endif
  2768. #endif // No else needed: Dynamic loops assumed.
  2769. ////////////////////////////////// CONSTANTS /////////////////////////////////
  2770. // The larger the resized tile, the fewer samples we'll need for downsizing.
  2771. // See if we can get a static min tile size > mask_min_allowed_tile_size:
  2772. static const float mask_min_allowed_tile_size = ceil(
  2773. mask_min_allowed_triad_size * mask_triads_per_tile);
  2774. static const float mask_min_expected_tile_size =
  2775. mask_min_allowed_tile_size;
  2776. // Limit the number of sinc resize taps by the maximum minification factor:
  2777. static const float pi_over_lobes = pi/mask_sinc_lobes;
  2778. static const float max_sinc_resize_samples_float = 2.0 * mask_sinc_lobes *
  2779. mask_resize_src_lut_size.x/mask_min_expected_tile_size;
  2780. // Vectorized loops sample in multiples of 4. Round up to be safe:
  2781. static const float max_sinc_resize_samples_m4 = ceil(
  2782. max_sinc_resize_samples_float * 0.25) * 4.0;
  2783. ///////////////////////// RESAMPLING FUNCTION HELPERS ////////////////////////
  2784. inline float get_dynamic_loop_size(const float magnification_scale)
  2785. {
  2786. // Requires: The following global constants must be defined:
  2787. // 1.) mask_sinc_lobes
  2788. // 2.) max_sinc_resize_samples_m4
  2789. // Returns: The minimum number of texture samples for a correct downsize
  2790. // at magnification_scale.
  2791. // We're downsizing, so the filter is sized across 2*lobes output pixels
  2792. // (not 2*lobes input texels). This impacts distance measurements and the
  2793. // minimum number of input samples needed.
  2794. const float min_samples_float = 2.0 * mask_sinc_lobes / magnification_scale;
  2795. const float min_samples_m4 = ceil(min_samples_float * 0.25) * 4.0;
  2796. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  2797. const float max_samples_m4 = max_sinc_resize_samples_m4;
  2798. #else // ifdef BREAK_LOOPS_INTO_PIECES
  2799. // Simulating loops with branches imposes a 128-sample limit.
  2800. const float max_samples_m4 = min(128.0, max_sinc_resize_samples_m4);
  2801. #endif
  2802. return min(min_samples_m4, max_samples_m4);
  2803. }
  2804. float2 get_first_texel_tile_uv_and_dist(const float2 tex_uv,
  2805. const float2 tex_size, const float dr,
  2806. const float input_tiles_per_texture_r, const float samples,
  2807. static const bool vertical)
  2808. {
  2809. // Requires: 1.) dr == du == 1.0/texture_size.x or
  2810. // dr == dv == 1.0/texture_size.y
  2811. // (whichever direction we're resampling in).
  2812. // It's a scalar to save register space.
  2813. // 2.) input_tiles_per_texture_r is the number of input tiles
  2814. // that can fit in the input texture in the direction we're
  2815. // resampling this pass.
  2816. // 3.) vertical indicates whether we're resampling vertically
  2817. // this pass (or horizontally).
  2818. // Returns: Pack and return the first sample's tile_uv coord in [0, 1]
  2819. // and its texel distance from the destination pixel, in the
  2820. // resized dimension only.
  2821. // We'll start with the topmost or leftmost sample and work down or right,
  2822. // so get the first sample location and distance. Modify both dimensions
  2823. // as if we're doing a one-pass 2D resize; we'll throw away the unneeded
  2824. // (and incorrect) dimension at the end.
  2825. const float2 curr_texel = tex_uv * tex_size;
  2826. const float2 prev_texel =
  2827. floor(curr_texel - float2(under_half)) + float2(0.5);
  2828. const float2 first_texel = prev_texel - float2(samples/2.0 - 1.0);
  2829. const float2 first_texel_uv_wrap_2D = first_texel * dr;
  2830. const float2 first_texel_dist_2D = curr_texel - first_texel;
  2831. // Convert from tex_uv to tile_uv coords so we can sub fracs for fmods.
  2832. const float2 first_texel_tile_uv_wrap_2D =
  2833. first_texel_uv_wrap_2D * input_tiles_per_texture_r;
  2834. // Project wrapped coordinates to the [0, 1] range. We'll do this with all
  2835. // samples,but the first texel is special, since it might be negative.
  2836. const float2 coord_negative =
  2837. float2((first_texel_tile_uv_wrap_2D.x < 0.),(first_texel_tile_uv_wrap_2D.y < 0.));
  2838. const float2 first_texel_tile_uv_2D =
  2839. frac(first_texel_tile_uv_wrap_2D) + coord_negative;
  2840. // Pack the first texel's tile_uv coord and texel distance in 1D:
  2841. const float2 tile_u_and_dist =
  2842. float2(first_texel_tile_uv_2D.x, first_texel_dist_2D.x);
  2843. const float2 tile_v_and_dist =
  2844. float2(first_texel_tile_uv_2D.y, first_texel_dist_2D.y);
  2845. return vertical ? tile_v_and_dist : tile_u_and_dist;
  2846. //return lerp(tile_u_and_dist, tile_v_and_dist, float(vertical));
  2847. }
  2848. inline float4 tex2Dlod0try(const sampler2D tex, const float2 tex_uv)
  2849. {
  2850. // Mipmapping and anisotropic filtering get confused by sinc-resampling.
  2851. // One [slow] workaround is to select the lowest mip level:
  2852. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2853. return textureLod(tex, float4(tex_uv, 0.0, 0.0).xy);
  2854. #else
  2855. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2856. return tex2Dbias(tex, float4(tex_uv, 0.0, -16.0));
  2857. #else
  2858. return texture(tex, tex_uv);
  2859. #endif
  2860. #endif
  2861. }
  2862. ////////////////////////////// LOOP BODY MACROS //////////////////////////////
  2863. // Using inline functions can exceed the temporary register limit, so we're
  2864. // stuck with #define macros (I'm TRULY sorry). They're declared here instead
  2865. // of above to be closer to the actual invocation sites. Steps:
  2866. // 1.) Get the exact texel location.
  2867. // 2.) Sample the phosphor mask (already assumed encoded in linear RGB).
  2868. // 3.) Get the distance from the current pixel and sinc weight:
  2869. // sinc(dist) = sin(pi * dist)/(pi * dist)
  2870. // We can also use the slower/smoother Lanczos instead:
  2871. // L(x) = sinc(dist) * sinc(dist / lobes)
  2872. // 4.) Accumulate the weight sum in weights, and accumulate the weighted texels
  2873. // in pixel_color (we'll normalize outside the loop at the end).
  2874. // We vectorize the loop to help reduce the Lanczos window's cost.
  2875. // The r coord is the coord in the dimension we're resizing along (u or v),
  2876. // and first_texel_tile_uv_rrrr is a float4 of the first texel's u or v
  2877. // tile_uv coord in [0, 1]. tex_uv_r will contain the tile_uv u or v coord
  2878. // for four new texel samples.
  2879. #define CALCULATE_R_COORD_FOR_4_SAMPLES \
  2880. const float4 true_i = float4(i_base + i) + float4(0.0, 1.0, 2.0, 3.0); \
  2881. const float4 tile_uv_r = frac( \
  2882. first_texel_tile_uv_rrrr + true_i * tile_dr); \
  2883. const float4 tex_uv_r = tile_uv_r * tile_size_uv_r;
  2884. #ifdef PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  2885. #define CALCULATE_SINC_RESAMPLE_WEIGHTS \
  2886. const float4 pi_dist_over_lobes = pi_over_lobes * dist; \
  2887. const float4 weights = min(sin(pi_dist) * sin(pi_dist_over_lobes) /\
  2888. (pi_dist*pi_dist_over_lobes), float4(1.0));
  2889. #else
  2890. #define CALCULATE_SINC_RESAMPLE_WEIGHTS \
  2891. const float4 weights = min(sin(pi_dist)/pi_dist, float4(1.0));
  2892. #endif
  2893. #define UPDATE_COLOR_AND_WEIGHT_SUMS \
  2894. const float4 dist = magnification_scale * \
  2895. abs(first_dist_unscaled - true_i); \
  2896. const float4 pi_dist = pi * dist; \
  2897. CALCULATE_SINC_RESAMPLE_WEIGHTS; \
  2898. pixel_color += new_sample0 * weights.xxx; \
  2899. pixel_color += new_sample1 * weights.yyy; \
  2900. pixel_color += new_sample2 * weights.zzz; \
  2901. pixel_color += new_sample3 * weights.www; \
  2902. weight_sum += weights;
  2903. #define VERTICAL_SINC_RESAMPLE_LOOP_BODY \
  2904. CALCULATE_R_COORD_FOR_4_SAMPLES; \
  2905. const float3 new_sample0 = tex2Dlod0try(tex, \
  2906. float2(tex_uv.x, tex_uv_r.x)).rgb; \
  2907. const float3 new_sample1 = tex2Dlod0try(tex, \
  2908. float2(tex_uv.x, tex_uv_r.y)).rgb; \
  2909. const float3 new_sample2 = tex2Dlod0try(tex, \
  2910. float2(tex_uv.x, tex_uv_r.z)).rgb; \
  2911. const float3 new_sample3 = tex2Dlod0try(tex, \
  2912. float2(tex_uv.x, tex_uv_r.w)).rgb; \
  2913. UPDATE_COLOR_AND_WEIGHT_SUMS;
  2914. #define HORIZONTAL_SINC_RESAMPLE_LOOP_BODY \
  2915. CALCULATE_R_COORD_FOR_4_SAMPLES; \
  2916. const float3 new_sample0 = tex2Dlod0try(tex, \
  2917. float2(tex_uv_r.x, tex_uv.y)).rgb; \
  2918. const float3 new_sample1 = tex2Dlod0try(tex, \
  2919. float2(tex_uv_r.y, tex_uv.y)).rgb; \
  2920. const float3 new_sample2 = tex2Dlod0try(tex, \
  2921. float2(tex_uv_r.z, tex_uv.y)).rgb; \
  2922. const float3 new_sample3 = tex2Dlod0try(tex, \
  2923. float2(tex_uv_r.w, tex_uv.y)).rgb; \
  2924. UPDATE_COLOR_AND_WEIGHT_SUMS;
  2925. //////////////////////////// RESAMPLING FUNCTIONS ////////////////////////////
  2926. float3 downsample_vertical_sinc_tiled(const sampler2D tex,
  2927. const float2 tex_uv, const float2 tex_size, static const float dr,
  2928. const float magnification_scale, static const float tile_size_uv_r)
  2929. {
  2930. // Requires: 1.) dr == du == 1.0/texture_size.x or
  2931. // dr == dv == 1.0/texture_size.y
  2932. // (whichever direction we're resampling in).
  2933. // It's a scalar to save register space.
  2934. // 2.) tile_size_uv_r is the number of texels an input tile
  2935. // takes up in the input texture, in the direction we're
  2936. // resampling this pass.
  2937. // 3.) magnification_scale must be <= 1.0.
  2938. // Returns: Return a [Lanczos] sinc-resampled pixel of a vertically
  2939. // downsized input tile embedded in an input texture. (The
  2940. // vertical version is special-cased though: It assumes the
  2941. // tile size equals the [static] texture size, since it's used
  2942. // on an LUT texture input containing one tile. For more
  2943. // generic use, eliminate the "static" in the parameters.)
  2944. // The "r" in "dr," "tile_size_uv_r," etc. refers to the dimension
  2945. // we're resizing along, e.g. "dy" in this case.
  2946. #ifdef USE_SINGLE_STATIC_LOOP
  2947. // A static loop can be faster, but it might blur too much from using
  2948. // more samples than it should.
  2949. static const int samples = int(max_sinc_resize_samples_m4);
  2950. #else
  2951. const int samples = int(get_dynamic_loop_size(magnification_scale));
  2952. #endif
  2953. // Get the first sample location (scalar tile uv coord along the resized
  2954. // dimension) and distance from the output location (in texels):
  2955. static const float input_tiles_per_texture_r = 1.0/tile_size_uv_r;
  2956. // true = vertical resize:
  2957. const float2 first_texel_tile_r_and_dist = get_first_texel_tile_uv_and_dist(
  2958. tex_uv, tex_size, dr, input_tiles_per_texture_r, samples, true);
  2959. const float4 first_texel_tile_uv_rrrr = first_texel_tile_r_and_dist.xxxx;
  2960. const float4 first_dist_unscaled = first_texel_tile_r_and_dist.yyyy;
  2961. // Get the tile sample offset:
  2962. static const float tile_dr = dr * input_tiles_per_texture_r;
  2963. // Sum up each weight and weighted sample color, varying the looping
  2964. // strategy based on our expected dynamic loop capabilities. See the
  2965. // loop body macros above.
  2966. int i_base = 0;
  2967. float4 weight_sum = float4(0.0);
  2968. float3 pixel_color = float3(0.0);
  2969. static const int i_step = 4;
  2970. #ifdef BREAK_LOOPS_INTO_PIECES
  2971. if(samples - i_base >= 64)
  2972. {
  2973. for(int i = 0; i < 64; i += i_step)
  2974. {
  2975. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  2976. }
  2977. i_base += 64;
  2978. }
  2979. if(samples - i_base >= 32)
  2980. {
  2981. for(int i = 0; i < 32; i += i_step)
  2982. {
  2983. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  2984. }
  2985. i_base += 32;
  2986. }
  2987. if(samples - i_base >= 16)
  2988. {
  2989. for(int i = 0; i < 16; i += i_step)
  2990. {
  2991. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  2992. }
  2993. i_base += 16;
  2994. }
  2995. if(samples - i_base >= 8)
  2996. {
  2997. for(int i = 0; i < 8; i += i_step)
  2998. {
  2999. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  3000. }
  3001. i_base += 8;
  3002. }
  3003. if(samples - i_base >= 4)
  3004. {
  3005. for(int i = 0; i < 4; i += i_step)
  3006. {
  3007. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  3008. }
  3009. i_base += 4;
  3010. }
  3011. // Do another 4-sample block for a total of 128 max samples.
  3012. if(samples - i_base > 0)
  3013. {
  3014. for(int i = 0; i < 4; i += i_step)
  3015. {
  3016. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  3017. }
  3018. }
  3019. #else
  3020. for(int i = 0; i < samples; i += i_step)
  3021. {
  3022. VERTICAL_SINC_RESAMPLE_LOOP_BODY;
  3023. }
  3024. #endif
  3025. // Normalize so the weight_sum == 1.0, and return:
  3026. const float2 weight_sum_reduce = weight_sum.xy + weight_sum.zw;
  3027. const float3 scalar_weight_sum = float3(weight_sum_reduce.x +
  3028. weight_sum_reduce.y);
  3029. return (pixel_color/scalar_weight_sum);
  3030. }
  3031. float3 downsample_horizontal_sinc_tiled(const sampler2D tex,
  3032. const float2 tex_uv, const float2 tex_size, const float dr,
  3033. const float magnification_scale, const float tile_size_uv_r)
  3034. {
  3035. // Differences from downsample_horizontal_sinc_tiled:
  3036. // 1.) The dr and tile_size_uv_r parameters are not static consts.
  3037. // 2.) The "vertical" parameter to get_first_texel_tile_uv_and_dist is
  3038. // set to false instead of true.
  3039. // 3.) The horizontal version of the loop body is used.
  3040. // TODO: If we can get guaranteed compile-time dead code elimination,
  3041. // we can combine the vertical/horizontal downsampling functions by:
  3042. // 1.) Add an extra static const bool parameter called "vertical."
  3043. // 2.) Supply it with the result of get_first_texel_tile_uv_and_dist().
  3044. // 3.) Use a conditional assignment in the loop body macro. This is the
  3045. // tricky part: We DO NOT want to incur the extra conditional
  3046. // assignment in the inner loop at runtime!
  3047. // The "r" in "dr," "tile_size_uv_r," etc. refers to the dimension
  3048. // we're resizing along, e.g. "dx" in this case.
  3049. #ifdef USE_SINGLE_STATIC_LOOP
  3050. // If we have to load all samples, we might as well use them.
  3051. static const int samples = int(max_sinc_resize_samples_m4);
  3052. #else
  3053. const int samples = int(get_dynamic_loop_size(magnification_scale));
  3054. #endif
  3055. // Get the first sample location (scalar tile uv coord along resized
  3056. // dimension) and distance from the output location (in texels):
  3057. const float input_tiles_per_texture_r = 1.0/tile_size_uv_r;
  3058. // false = horizontal resize:
  3059. const float2 first_texel_tile_r_and_dist = get_first_texel_tile_uv_and_dist(
  3060. tex_uv, tex_size, dr, input_tiles_per_texture_r, samples, false);
  3061. const float4 first_texel_tile_uv_rrrr = first_texel_tile_r_and_dist.xxxx;
  3062. const float4 first_dist_unscaled = first_texel_tile_r_and_dist.yyyy;
  3063. // Get the tile sample offset:
  3064. const float tile_dr = dr * input_tiles_per_texture_r;
  3065. // Sum up each weight and weighted sample color, varying the looping
  3066. // strategy based on our expected dynamic loop capabilities. See the
  3067. // loop body macros above.
  3068. int i_base = 0;
  3069. float4 weight_sum = float4(0.0);
  3070. float3 pixel_color = float3(0.0);
  3071. static const int i_step = 4;
  3072. #ifdef BREAK_LOOPS_INTO_PIECES
  3073. if(samples - i_base >= 64)
  3074. {
  3075. for(int i = 0; i < 64; i += i_step)
  3076. {
  3077. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3078. }
  3079. i_base += 64;
  3080. }
  3081. if(samples - i_base >= 32)
  3082. {
  3083. for(int i = 0; i < 32; i += i_step)
  3084. {
  3085. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3086. }
  3087. i_base += 32;
  3088. }
  3089. if(samples - i_base >= 16)
  3090. {
  3091. for(int i = 0; i < 16; i += i_step)
  3092. {
  3093. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3094. }
  3095. i_base += 16;
  3096. }
  3097. if(samples - i_base >= 8)
  3098. {
  3099. for(int i = 0; i < 8; i += i_step)
  3100. {
  3101. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3102. }
  3103. i_base += 8;
  3104. }
  3105. if(samples - i_base >= 4)
  3106. {
  3107. for(int i = 0; i < 4; i += i_step)
  3108. {
  3109. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3110. }
  3111. i_base += 4;
  3112. }
  3113. // Do another 4-sample block for a total of 128 max samples.
  3114. if(samples - i_base > 0)
  3115. {
  3116. for(int i = 0; i < 4; i += i_step)
  3117. {
  3118. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3119. }
  3120. }
  3121. #else
  3122. for(int i = 0; i < samples; i += i_step)
  3123. {
  3124. HORIZONTAL_SINC_RESAMPLE_LOOP_BODY;
  3125. }
  3126. #endif
  3127. // Normalize so the weight_sum == 1.0, and return:
  3128. const float2 weight_sum_reduce = weight_sum.xy + weight_sum.zw;
  3129. const float3 scalar_weight_sum = float3(weight_sum_reduce.x +
  3130. weight_sum_reduce.y);
  3131. return (pixel_color/scalar_weight_sum);
  3132. }
  3133. //////////////////////////// TILE SIZE CALCULATION ///////////////////////////
  3134. float2 get_resized_mask_tile_size(const float2 estimated_viewport_size,
  3135. const float2 estimated_mask_resize_output_size,
  3136. const bool solemnly_swear_same_inputs_for_every_pass)
  3137. {
  3138. // Requires: The following global constants must be defined according to
  3139. // certain constraints:
  3140. // 1.) mask_resize_num_triads: Must be high enough that our
  3141. // mask sampling method won't have artifacts later
  3142. // (long story; see derived-settings-and-constants.h)
  3143. // 2.) mask_resize_src_lut_size: Texel size of our mask LUT
  3144. // 3.) mask_triads_per_tile: Num horizontal triads in our LUT
  3145. // 4.) mask_min_allowed_triad_size: User setting (the more
  3146. // restrictive it is, the faster the resize will go)
  3147. // 5.) mask_min_allowed_tile_size_x < mask_resize_src_lut_size.x
  3148. // 6.) mask_triad_size_desired_{runtime, static}
  3149. // 7.) mask_num_triads_desired_{runtime, static}
  3150. // 8.) mask_specify_num_triads must be 0.0/1.0 (false/true)
  3151. // The function parameters must be defined as follows:
  3152. // 1.) estimated_viewport_size == (final viewport size);
  3153. // If mask_specify_num_triads is 1.0/true and the viewport
  3154. // estimate is wrong, the number of triads will differ from
  3155. // the user's preference by about the same factor.
  3156. // 2.) estimated_mask_resize_output_size: Must equal the
  3157. // output size of the MASK_RESIZE pass.
  3158. // Exception: The x component may be estimated garbage if
  3159. // and only if the caller throws away the x result.
  3160. // 3.) solemnly_swear_same_inputs_for_every_pass: Set to false,
  3161. // unless you can guarantee that every call across every
  3162. // pass will use the same sizes for the other parameters.
  3163. // When calling this across multiple passes, always use the
  3164. // same y viewport size/scale, and always use the same x
  3165. // viewport size/scale when using the x result.
  3166. // Returns: Return the final size of a manually resized mask tile, after
  3167. // constraining the desired size to avoid artifacts. Under
  3168. // unusual circumstances, tiles may become stretched vertically
  3169. // (see wall of text below).
  3170. // Stated tile properties must be correct:
  3171. static const float tile_aspect_ratio_inv =
  3172. mask_resize_src_lut_size.y/mask_resize_src_lut_size.x;
  3173. static const float tile_aspect_ratio = 1.0/tile_aspect_ratio_inv;
  3174. static const float2 tile_aspect = float2(1.0, tile_aspect_ratio_inv);
  3175. // If mask_specify_num_triads is 1.0/true and estimated_viewport_size.x is
  3176. // wrong, the user preference will be misinterpreted:
  3177. const float desired_tile_size_x = mask_triads_per_tile * lerp(
  3178. mask_triad_size_desired,
  3179. estimated_viewport_size.x / mask_num_triads_desired,
  3180. mask_specify_num_triads);
  3181. if(get_mask_sample_mode() > 0.5)
  3182. {
  3183. // We don't need constraints unless we're sampling MASK_RESIZE.
  3184. return desired_tile_size_x * tile_aspect;
  3185. }
  3186. // Make sure we're not upsizing:
  3187. const float temp_tile_size_x =
  3188. min(desired_tile_size_x, mask_resize_src_lut_size.x);
  3189. // Enforce min_tile_size and max_tile_size in both dimensions:
  3190. const float2 temp_tile_size = temp_tile_size_x * tile_aspect;
  3191. static const float2 min_tile_size =
  3192. mask_min_allowed_tile_size * tile_aspect;
  3193. const float2 max_tile_size =
  3194. estimated_mask_resize_output_size / mask_resize_num_tiles;
  3195. const float2 clamped_tile_size =
  3196. clamp(temp_tile_size, min_tile_size, max_tile_size);
  3197. // Try to maintain tile_aspect_ratio. This is the tricky part:
  3198. // If we're currently resizing in the y dimension, the x components
  3199. // could be MEANINGLESS. (If estimated_mask_resize_output_size.x is
  3200. // bogus, then so is max_tile_size.x and clamped_tile_size.x.)
  3201. // We can't adjust the y size based on clamped_tile_size.x. If it
  3202. // clamps when it shouldn't, it won't clamp again when later passes
  3203. // call this function with the correct sizes, and the discrepancy will
  3204. // break the sampling coords in MASKED_SCANLINES. Instead, we'll limit
  3205. // the x size based on the y size, but not vice versa, unless the
  3206. // caller swears the parameters were the same (correct) in every pass.
  3207. // As a result, triads could appear vertically stretched if:
  3208. // a.) mask_resize_src_lut_size.x > mask_resize_src_lut_size.y: Wide
  3209. // LUT's might clamp x more than y (all provided LUT's are square)
  3210. // b.) true_viewport_size.x < true_viewport_size.y: The user is playing
  3211. // with a vertically oriented screen (not accounted for anyway)
  3212. // c.) mask_resize_viewport_scale.x < masked_resize_viewport_scale.y:
  3213. // Viewport scales are equal by default.
  3214. // If any of these are the case, you can fix the stretching by setting:
  3215. // mask_resize_viewport_scale.x = mask_resize_viewport_scale.y *
  3216. // (1.0 / min_expected_aspect_ratio) *
  3217. // (mask_resize_src_lut_size.x / mask_resize_src_lut_size.y)
  3218. const float x_tile_size_from_y =
  3219. clamped_tile_size.y * tile_aspect_ratio;
  3220. const float y_tile_size_from_x = lerp(clamped_tile_size.y,
  3221. clamped_tile_size.x * tile_aspect_ratio_inv,
  3222. float(solemnly_swear_same_inputs_for_every_pass));
  3223. const float2 reclamped_tile_size = float2(
  3224. min(clamped_tile_size.x, x_tile_size_from_y),
  3225. min(clamped_tile_size.y, y_tile_size_from_x));
  3226. // We need integer tile sizes in both directions for tiled sampling to
  3227. // work correctly. Use floor (to make sure we don't round up), but be
  3228. // careful to avoid a rounding bug where floor decreases whole numbers:
  3229. const float2 final_resized_tile_size =
  3230. floor(reclamped_tile_size + float2(FIX_ZERO(0.0)));
  3231. return final_resized_tile_size;
  3232. }
  3233. ///////////////////////// FINAL MASK SAMPLING HELPERS ////////////////////////
  3234. float4 get_mask_sampling_parameters(const float2 mask_resize_texture_size,
  3235. const float2 mask_resize_video_size, const float2 true_viewport_size,
  3236. out float2 mask_tiles_per_screen)
  3237. {
  3238. // Requires: 1.) Requirements of get_resized_mask_tile_size() must be
  3239. // met, particularly regarding global constants.
  3240. // The function parameters must be defined as follows:
  3241. // 1.) mask_resize_texture_size == MASK_RESIZE.texture_size
  3242. // if get_mask_sample_mode() is 0 (otherwise anything)
  3243. // 2.) mask_resize_video_size == MASK_RESIZE.video_size
  3244. // if get_mask_sample_mode() is 0 (otherwise anything)
  3245. // 3.) true_viewport_size == output_size for a pass set to
  3246. // 1.0 viewport scale (i.e. it must be correct)
  3247. // Returns: Return a float4 containing:
  3248. // xy: tex_uv coords for the start of the mask tile
  3249. // zw: tex_uv size of the mask tile from start to end
  3250. // mask_tiles_per_screen is an out parameter containing the
  3251. // number of mask tiles that will fit on the screen.
  3252. // First get the final resized tile size. The viewport size and mask
  3253. // resize viewport scale must be correct, but don't solemnly swear they
  3254. // were correct in both mask resize passes unless you know it's true.
  3255. // (We can better ensure a correct tile aspect ratio if the parameters are
  3256. // guaranteed correct in all passes...but if we lie, we'll get inconsistent
  3257. // sizes across passes, resulting in broken texture coordinates.)
  3258. const float mask_sample_mode = get_mask_sample_mode();
  3259. const float2 mask_resize_tile_size = get_resized_mask_tile_size(
  3260. true_viewport_size, mask_resize_video_size, false);
  3261. if(mask_sample_mode < 0.5)
  3262. {
  3263. // Sample MASK_RESIZE: The resized tile is a fraction of the texture
  3264. // size and starts at a nonzero offset to allow for border texels:
  3265. const float2 mask_tile_uv_size = mask_resize_tile_size /
  3266. mask_resize_texture_size;
  3267. const float2 skipped_tiles = mask_start_texels/mask_resize_tile_size;
  3268. const float2 mask_tile_start_uv = skipped_tiles * mask_tile_uv_size;
  3269. // mask_tiles_per_screen must be based on the *true* viewport size:
  3270. mask_tiles_per_screen = true_viewport_size / mask_resize_tile_size;
  3271. return float4(mask_tile_start_uv, mask_tile_uv_size);
  3272. }
  3273. else
  3274. {
  3275. // If we're tiling at the original size (1:1 pixel:texel), redefine a
  3276. // "tile" to be the full texture containing many triads. Otherwise,
  3277. // we're hardware-resampling an LUT, and the texture truly contains a
  3278. // single unresized phosphor mask tile anyway.
  3279. static const float2 mask_tile_uv_size = float2(1.0);
  3280. static const float2 mask_tile_start_uv = float2(0.0);
  3281. if(mask_sample_mode > 1.5)
  3282. {
  3283. // Repeat the full LUT at a 1:1 pixel:texel ratio without resizing:
  3284. mask_tiles_per_screen = true_viewport_size/mask_texture_large_size;
  3285. }
  3286. else
  3287. {
  3288. // Hardware-resize the original LUT:
  3289. mask_tiles_per_screen = true_viewport_size / mask_resize_tile_size;
  3290. }
  3291. return float4(mask_tile_start_uv, mask_tile_uv_size);
  3292. }
  3293. }
  3294. /*
  3295. float2 fix_tiling_discontinuities_normalized(const float2 tile_uv,
  3296. float2 duv_dx, float2 duv_dy)
  3297. {
  3298. // Requires: 1.) duv_dx == ddx(tile_uv)
  3299. // 2.) duv_dy == ddy(tile_uv)
  3300. // 3.) tile_uv contains tile-relative uv coords in [0, 1],
  3301. // such that (0.5, 0.5) is the center of a tile, etc.
  3302. // ("Tile" can mean texture, the video embedded in the
  3303. // texture, or some other "tile" embedded in a texture.)
  3304. // Returns: Return new tile_uv coords that contain no discontinuities
  3305. // across a 2x2 pixel quad.
  3306. // Description:
  3307. // When uv coords wrap from 1.0 to 0.0, they create a discontinuity in the
  3308. // derivatives, which we assume happened if the absolute difference between
  3309. // any fragment in a 2x2 block is > ~half a tile. If the current block has
  3310. // a u or v discontinuity and the current fragment is in the first half of
  3311. // the tile along that axis (i.e. it wrapped from 1.0 to 0.0), add a tile
  3312. // to that coord to make the 2x2 block continuous. (It will now have a
  3313. // coord > 1.0 in the padding area beyond the tile.) This function takes
  3314. // derivatives as parameters so the caller can reuse them.
  3315. // In case we're using high-quality (nVidia-style) derivatives, ensure
  3316. // diagonically opposite fragments see each other for correctness:
  3317. duv_dx = abs(duv_dx) + abs(ddy(duv_dx));
  3318. duv_dy = abs(duv_dy) + abs(ddx(duv_dy));
  3319. const float2 pixel_in_first_half_tile = float2((tile_uv.x < 0.5),(tile_uv.y < 0.5));
  3320. const float2 jump_exists = float2(((duv_dx + duv_dy).x > 0.5),((duv_dx + duv_dy).y > 0.5));
  3321. return tile_uv + jump_exists * pixel_in_first_half_tile;
  3322. }
  3323. */
  3324. float2 convert_phosphor_tile_uv_wrap_to_tex_uv(const float2 tile_uv_wrap,
  3325. const float4 mask_tile_start_uv_and_size)
  3326. {
  3327. // Requires: 1.) tile_uv_wrap contains tile-relative uv coords, where the
  3328. // tile spans from [0, 1], such that (0.5, 0.5) is at the
  3329. // tile center. The input coords can range from [0, inf],
  3330. // and their fractional parts map to a repeated tile.
  3331. // ("Tile" can mean texture, the video embedded in the
  3332. // texture, or some other "tile" embedded in a texture.)
  3333. // 2.) mask_tile_start_uv_and_size.xy contains tex_uv coords
  3334. // for the start of the embedded tile in the full texture.
  3335. // 3.) mask_tile_start_uv_and_size.zw contains the [fractional]
  3336. // tex_uv size of the embedded tile in the full texture.
  3337. // Returns: Return tex_uv coords (used for texture sampling)
  3338. // corresponding to tile_uv_wrap.
  3339. if(get_mask_sample_mode() < 0.5)
  3340. {
  3341. // Manually repeat the resized mask tile to fill the screen:
  3342. // First get fractional tile_uv coords. Using frac/fmod on coords
  3343. // confuses anisotropic filtering; fix it as user options dictate.
  3344. // derived-settings-and-constants.h disables incompatible options.
  3345. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  3346. float2 tile_uv = frac(tile_uv_wrap * 0.5) * 2.0;
  3347. #else
  3348. float2 tile_uv = frac(tile_uv_wrap);
  3349. #endif
  3350. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  3351. const float2 tile_uv_dx = ddx(tile_uv);
  3352. const float2 tile_uv_dy = ddy(tile_uv);
  3353. tile_uv = fix_tiling_discontinuities_normalized(tile_uv,
  3354. tile_uv_dx, tile_uv_dy);
  3355. #endif
  3356. // The tile is embedded in a padded FBO, and it may start at a
  3357. // nonzero offset if border texels are used to avoid artifacts:
  3358. const float2 mask_tex_uv = mask_tile_start_uv_and_size.xy +
  3359. tile_uv * mask_tile_start_uv_and_size.zw;
  3360. return mask_tex_uv;
  3361. }
  3362. else
  3363. {
  3364. // Sample from the input phosphor mask texture with hardware tiling.
  3365. // If we're tiling at the original size (mode 2), the "tile" is the
  3366. // whole texture, and it contains a large number of triads mapped with
  3367. // a 1:1 pixel:texel ratio. OTHERWISE, the texture contains a single
  3368. // unresized tile. tile_uv_wrap already has correct coords for both!
  3369. return tile_uv_wrap;
  3370. }
  3371. }
  3372. #endif // PHOSPHOR_MASK_RESIZING_H
  3373. ///////////////////////// END PHOSPHOR-MASK-RESIZING /////////////////////////
  3374. //#include "scanline-functions.h"
  3375. ///////////////////////////// BEGIN SCANLINE-FUNCTIONS ////////////////////////////
  3376. #ifndef SCANLINE_FUNCTIONS_H
  3377. #define SCANLINE_FUNCTIONS_H
  3378. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  3379. // crt-royale: A full-featured CRT shader, with cheese.
  3380. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  3381. //
  3382. // This program is free software; you can redistribute it and/or modify it
  3383. // under the terms of the GNU General Public License as published by the Free
  3384. // Software Foundation; either version 2 of the License, or any later version.
  3385. //
  3386. // This program is distributed in the hope that it will be useful, but WITHOUT
  3387. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  3388. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  3389. // more details.
  3390. //
  3391. // You should have received a copy of the GNU General Public License along with
  3392. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  3393. // Place, Suite 330, Boston, MA 02111-1307 USA
  3394. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  3395. //#include "../user-settings.h"
  3396. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  3397. #ifndef USER_SETTINGS_H
  3398. #define USER_SETTINGS_H
  3399. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  3400. // The Cg compiler uses different "profiles" with different capabilities.
  3401. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  3402. // require higher profiles like fp30 or fp40. The shader can't detect profile
  3403. // or driver capabilities, so instead you must comment or uncomment the lines
  3404. // below with "//" before "#define." Disable an option if you get compilation
  3405. // errors resembling those listed. Generally speaking, all of these options
  3406. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  3407. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  3408. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  3409. // Among other things, derivatives help us fix anisotropic filtering artifacts
  3410. // with curved manually tiled phosphor mask coords. Related errors:
  3411. // error C3004: function "float2 ddx(float2);" not supported in this profile
  3412. // error C3004: function "float2 ddy(float2);" not supported in this profile
  3413. //#define DRIVERS_ALLOW_DERIVATIVES
  3414. // Fine derivatives: Unsupported on older ATI cards.
  3415. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  3416. // fast single-pass blur operations. If your card uses coarse derivatives and
  3417. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  3418. #ifdef DRIVERS_ALLOW_DERIVATIVES
  3419. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  3420. #endif
  3421. // Dynamic looping: Requires an fp30 or newer profile.
  3422. // This makes phosphor mask resampling faster in some cases. Related errors:
  3423. // error C5013: profile does not support "for" statements and "for" could not
  3424. // be unrolled
  3425. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  3426. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  3427. // Using one static loop avoids overhead if the user is right, but if the user
  3428. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  3429. // binary search can potentially save some iterations. However, it may fail:
  3430. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  3431. // needed to compile program
  3432. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  3433. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  3434. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  3435. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  3436. // this profile
  3437. //#define DRIVERS_ALLOW_TEX2DLOD
  3438. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  3439. // artifacts from anisotropic filtering and mipmapping. Related errors:
  3440. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  3441. // in this profile
  3442. //#define DRIVERS_ALLOW_TEX2DBIAS
  3443. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  3444. // impose stricter limitations on register counts and instructions. Enable
  3445. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  3446. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  3447. // to compile program.
  3448. // Enabling integrated graphics compatibility mode will automatically disable:
  3449. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  3450. // (This may be reenabled in a later release.)
  3451. // 2.) RUNTIME_GEOMETRY_MODE
  3452. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  3453. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  3454. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  3455. // To disable a #define option, turn its line into a comment with "//."
  3456. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  3457. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  3458. // many of the options in this file and allow real-time tuning, but many of
  3459. // them are slower. Disabling them and using this text file will boost FPS.
  3460. #define RUNTIME_SHADER_PARAMS_ENABLE
  3461. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  3462. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  3463. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  3464. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  3465. #define RUNTIME_ANTIALIAS_WEIGHTS
  3466. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  3467. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  3468. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  3469. // parameters? This will require more math or dynamic branching.
  3470. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  3471. // Specify the tilt at runtime? This makes things about 3% slower.
  3472. #define RUNTIME_GEOMETRY_TILT
  3473. // Specify the geometry mode at runtime?
  3474. #define RUNTIME_GEOMETRY_MODE
  3475. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  3476. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  3477. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  3478. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  3479. // PHOSPHOR MASK:
  3480. // Manually resize the phosphor mask for best results (slower)? Disabling this
  3481. // removes the option to do so, but it may be faster without dynamic branches.
  3482. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  3483. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  3484. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  3485. // Larger blurs are expensive, but we need them to blur larger triads. We can
  3486. // detect the right blur if the triad size is static or our profile allows
  3487. // dynamic branches, but otherwise we use the largest blur the user indicates
  3488. // they might need:
  3489. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  3490. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  3491. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  3492. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  3493. // Here's a helpful chart:
  3494. // MaxTriadSize BlurSize MinTriadCountsByResolution
  3495. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3496. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3497. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3498. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3499. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3500. /////////////////////////////// USER PARAMETERS //////////////////////////////
  3501. // Note: Many of these static parameters are overridden by runtime shader
  3502. // parameters when those are enabled. However, many others are static codepath
  3503. // options that were cleaner or more convert to code as static constants.
  3504. // GAMMA:
  3505. static const float crt_gamma_static = 2.5; // range [1, 5]
  3506. static const float lcd_gamma_static = 2.2; // range [1, 5]
  3507. // LEVELS MANAGEMENT:
  3508. // Control the final multiplicative image contrast:
  3509. static const float levels_contrast_static = 1.0; // range [0, 4)
  3510. // We auto-dim to avoid clipping between passes and restore brightness
  3511. // later. Control the dim factor here: Lower values clip less but crush
  3512. // blacks more (static only for now).
  3513. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  3514. // HALATION/DIFFUSION/BLOOM:
  3515. // Halation weight: How much energy should be lost to electrons bounding
  3516. // around under the CRT glass and exciting random phosphors?
  3517. static const float halation_weight_static = 0.0; // range [0, 1]
  3518. // Refractive diffusion weight: How much light should spread/diffuse from
  3519. // refracting through the CRT glass?
  3520. static const float diffusion_weight_static = 0.075; // range [0, 1]
  3521. // Underestimate brightness: Bright areas bloom more, but we can base the
  3522. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  3523. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  3524. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  3525. // Blur all colors more than necessary for a softer phosphor bloom?
  3526. static const float bloom_excess_static = 0.0; // range [0, 1]
  3527. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  3528. // blurred resize of the input (convergence offsets are applied as well).
  3529. // There are three filter options (static option only for now):
  3530. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  3531. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  3532. // and beam_max_sigma is low.
  3533. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  3534. // always uses a static sigma regardless of beam_max_sigma or
  3535. // mask_num_triads_desired.
  3536. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  3537. // These options are more pronounced for the fast, unbloomed shader version.
  3538. #ifndef RADEON_FIX
  3539. static const float bloom_approx_filter_static = 2.0;
  3540. #else
  3541. static const float bloom_approx_filter_static = 1.0;
  3542. #endif
  3543. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  3544. // How many scanlines should contribute light to each pixel? Using more
  3545. // scanlines is slower (especially for a generalized Gaussian) but less
  3546. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  3547. // max_beam_sigma at which the closest unused weight is guaranteed <
  3548. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  3549. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  3550. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  3551. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  3552. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  3553. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  3554. static const float beam_num_scanlines = 3.0; // range [2, 6]
  3555. // A generalized Gaussian beam varies shape with color too, now just width.
  3556. // It's slower but more flexible (static option only for now).
  3557. static const bool beam_generalized_gaussian = true;
  3558. // What kind of scanline antialiasing do you want?
  3559. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  3560. // Integrals are slow (especially for generalized Gaussians) and rarely any
  3561. // better than 3x antialiasing (static option only for now).
  3562. static const float beam_antialias_level = 1.0; // range [0, 2]
  3563. // Min/max standard deviations for scanline beams: Higher values widen and
  3564. // soften scanlines. Depending on other options, low min sigmas can alias.
  3565. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  3566. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  3567. // Beam width varies as a function of color: A power function (0) is more
  3568. // configurable, but a spherical function (1) gives the widest beam
  3569. // variability without aliasing (static option only for now).
  3570. static const float beam_spot_shape_function = 0.0;
  3571. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  3572. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  3573. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  3574. // Generalized Gaussian max shape parameters: Higher values give flatter
  3575. // scanline plateaus and steeper dropoffs, simultaneously widening and
  3576. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  3577. // values > ~40.0 cause artifacts with integrals.
  3578. static const float beam_min_shape_static = 2.0; // range [2, 32]
  3579. static const float beam_max_shape_static = 4.0; // range [2, 32]
  3580. // Generalized Gaussian shape power: Affects how quickly the distribution
  3581. // changes shape from Gaussian to steep/plateaued as color increases from 0
  3582. // to 1.0. Higher powers appear softer for most colors, and lower powers
  3583. // appear sharper for most colors.
  3584. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  3585. // What filter should be used to sample scanlines horizontally?
  3586. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  3587. static const float beam_horiz_filter_static = 0.0;
  3588. // Standard deviation for horizontal Gaussian resampling:
  3589. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  3590. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  3591. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  3592. // limiting circuitry in some CRT's), or a weighted avg.?
  3593. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  3594. // Simulate scanline misconvergence? This needs 3x horizontal texture
  3595. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  3596. // later passes (static option only for now).
  3597. static const bool beam_misconvergence = true;
  3598. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  3599. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  3600. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  3601. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  3602. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  3603. // Detect interlacing (static option only for now)?
  3604. static const bool interlace_detect = true;
  3605. // Assume 1080-line sources are interlaced?
  3606. static const bool interlace_1080i_static = false;
  3607. // For interlaced sources, assume TFF (top-field first) or BFF order?
  3608. // (Whether this matters depends on the nature of the interlaced input.)
  3609. static const bool interlace_bff_static = false;
  3610. // ANTIALIASING:
  3611. // What AA level do you want for curvature/overscan/subpixels? Options:
  3612. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  3613. // (Static option only for now)
  3614. static const float aa_level = 12.0; // range [0, 24]
  3615. // What antialiasing filter do you want (static option only)? Options:
  3616. // 0: Box (separable), 1: Box (cylindrical),
  3617. // 2: Tent (separable), 3: Tent (cylindrical),
  3618. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  3619. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  3620. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  3621. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  3622. static const float aa_filter = 6.0; // range [0, 9]
  3623. // Flip the sample grid on odd/even frames (static option only for now)?
  3624. static const bool aa_temporal = false;
  3625. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  3626. // the blue offset is the negative r offset; range [0, 0.5]
  3627. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  3628. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  3629. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  3630. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  3631. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  3632. // 4.) C = 0.0 is a soft spline filter.
  3633. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  3634. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  3635. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  3636. // PHOSPHOR MASK:
  3637. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  3638. static const float mask_type_static = 1.0; // range [0, 2]
  3639. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  3640. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  3641. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  3642. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  3643. // is halfway decent with LUT mipmapping but atrocious without it.
  3644. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  3645. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  3646. // This mode reuses the same masks, so triads will be enormous unless
  3647. // you change the mask LUT filenames in your .cgp file.
  3648. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  3649. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  3650. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  3651. // will always be used to calculate the full bloom sigma statically.
  3652. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  3653. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  3654. // triads) will be rounded to the nearest integer tile size and clamped to
  3655. // obey minimum size constraints (imposed to reduce downsize taps) and
  3656. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  3657. // To increase the size limit, double the viewport-relative scales for the
  3658. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  3659. // range [1, mask_texture_small_size/mask_triads_per_tile]
  3660. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  3661. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  3662. // final size will be rounded and constrained as above); default 480.0
  3663. static const float mask_num_triads_desired_static = 480.0;
  3664. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  3665. // more samples and avoid moire a bit better, but some is unavoidable
  3666. // depending on the destination size (static option for now).
  3667. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  3668. // The mask is resized using a variable number of taps in each dimension,
  3669. // but some Cg profiles always fetch a constant number of taps no matter
  3670. // what (no dynamic branching). We can limit the maximum number of taps if
  3671. // we statically limit the minimum phosphor triad size. Larger values are
  3672. // faster, but the limit IS enforced (static option only, forever);
  3673. // range [1, mask_texture_small_size/mask_triads_per_tile]
  3674. // TODO: Make this 1.0 and compensate with smarter sampling!
  3675. static const float mask_min_allowed_triad_size = 2.0;
  3676. // GEOMETRY:
  3677. // Geometry mode:
  3678. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  3679. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  3680. static const float geom_mode_static = 0.0; // range [0, 3]
  3681. // Radius of curvature: Measured in units of your viewport's diagonal size.
  3682. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  3683. // View dist is the distance from the player to their physical screen, in
  3684. // units of the viewport's diagonal size. It controls the field of view.
  3685. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  3686. // Tilt angle in radians (clockwise around up and right vectors):
  3687. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  3688. // Aspect ratio: When the true viewport size is unknown, this value is used
  3689. // to help convert between the phosphor triad size and count, along with
  3690. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  3691. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  3692. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  3693. // default (256/224)*(54/47) = 1.313069909 (see below)
  3694. static const float geom_aspect_ratio_static = 1.313069909;
  3695. // Before getting into overscan, here's some general aspect ratio info:
  3696. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  3697. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  3698. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  3699. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  3700. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  3701. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  3702. // a.) Enable Retroarch's "Crop Overscan"
  3703. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  3704. // Real consoles use horizontal black padding in the signal, but emulators
  3705. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  3706. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  3707. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  3708. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  3709. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  3710. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  3711. // without doing a. or b., but horizontal image borders will be tighter
  3712. // than vertical ones, messing up curvature and overscan. Fixing the
  3713. // padding first corrects this.
  3714. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  3715. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  3716. // above: Values < 1.0 zoom out; range (0, inf)
  3717. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  3718. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  3719. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  3720. // with strong curvature (static option only for now).
  3721. static const bool geom_force_correct_tangent_matrix = true;
  3722. // BORDERS:
  3723. // Rounded border size in texture uv coords:
  3724. static const float border_size_static = 0.015; // range [0, 0.5]
  3725. // Border darkness: Moderate values darken the border smoothly, and high
  3726. // values make the image very dark just inside the border:
  3727. static const float border_darkness_static = 2.0; // range [0, inf)
  3728. // Border compression: High numbers compress border transitions, narrowing
  3729. // the dark border area.
  3730. static const float border_compress_static = 2.5; // range [1, inf)
  3731. #endif // USER_SETTINGS_H
  3732. //////////////////////////// END USER-SETTINGS //////////////////////////
  3733. //#include "derived-settings-and-constants.h"
  3734. //////////////////// BEGIN DERIVED-SETTINGS-AND-CONSTANTS ////////////////////
  3735. #ifndef DERIVED_SETTINGS_AND_CONSTANTS_H
  3736. #define DERIVED_SETTINGS_AND_CONSTANTS_H
  3737. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  3738. // crt-royale: A full-featured CRT shader, with cheese.
  3739. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  3740. //
  3741. // This program is free software; you can redistribute it and/or modify it
  3742. // under the terms of the GNU General Public License as published by the Free
  3743. // Software Foundation; either version 2 of the License, or any later version.
  3744. //
  3745. // This program is distributed in the hope that it will be useful, but WITHOUT
  3746. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  3747. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  3748. // more details.
  3749. //
  3750. // You should have received a copy of the GNU General Public License along with
  3751. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  3752. // Place, Suite 330, Boston, MA 02111-1307 USA
  3753. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  3754. // These macros and constants can be used across the whole codebase.
  3755. // Unlike the values in user-settings.cgh, end users shouldn't modify these.
  3756. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  3757. //#include "../user-settings.h"
  3758. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  3759. #ifndef USER_SETTINGS_H
  3760. #define USER_SETTINGS_H
  3761. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  3762. // The Cg compiler uses different "profiles" with different capabilities.
  3763. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  3764. // require higher profiles like fp30 or fp40. The shader can't detect profile
  3765. // or driver capabilities, so instead you must comment or uncomment the lines
  3766. // below with "//" before "#define." Disable an option if you get compilation
  3767. // errors resembling those listed. Generally speaking, all of these options
  3768. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  3769. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  3770. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  3771. // Among other things, derivatives help us fix anisotropic filtering artifacts
  3772. // with curved manually tiled phosphor mask coords. Related errors:
  3773. // error C3004: function "float2 ddx(float2);" not supported in this profile
  3774. // error C3004: function "float2 ddy(float2);" not supported in this profile
  3775. //#define DRIVERS_ALLOW_DERIVATIVES
  3776. // Fine derivatives: Unsupported on older ATI cards.
  3777. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  3778. // fast single-pass blur operations. If your card uses coarse derivatives and
  3779. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  3780. #ifdef DRIVERS_ALLOW_DERIVATIVES
  3781. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  3782. #endif
  3783. // Dynamic looping: Requires an fp30 or newer profile.
  3784. // This makes phosphor mask resampling faster in some cases. Related errors:
  3785. // error C5013: profile does not support "for" statements and "for" could not
  3786. // be unrolled
  3787. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  3788. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  3789. // Using one static loop avoids overhead if the user is right, but if the user
  3790. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  3791. // binary search can potentially save some iterations. However, it may fail:
  3792. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  3793. // needed to compile program
  3794. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  3795. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  3796. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  3797. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  3798. // this profile
  3799. //#define DRIVERS_ALLOW_TEX2DLOD
  3800. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  3801. // artifacts from anisotropic filtering and mipmapping. Related errors:
  3802. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  3803. // in this profile
  3804. //#define DRIVERS_ALLOW_TEX2DBIAS
  3805. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  3806. // impose stricter limitations on register counts and instructions. Enable
  3807. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  3808. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  3809. // to compile program.
  3810. // Enabling integrated graphics compatibility mode will automatically disable:
  3811. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  3812. // (This may be reenabled in a later release.)
  3813. // 2.) RUNTIME_GEOMETRY_MODE
  3814. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  3815. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  3816. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  3817. // To disable a #define option, turn its line into a comment with "//."
  3818. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  3819. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  3820. // many of the options in this file and allow real-time tuning, but many of
  3821. // them are slower. Disabling them and using this text file will boost FPS.
  3822. #define RUNTIME_SHADER_PARAMS_ENABLE
  3823. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  3824. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  3825. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  3826. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  3827. #define RUNTIME_ANTIALIAS_WEIGHTS
  3828. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  3829. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  3830. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  3831. // parameters? This will require more math or dynamic branching.
  3832. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  3833. // Specify the tilt at runtime? This makes things about 3% slower.
  3834. #define RUNTIME_GEOMETRY_TILT
  3835. // Specify the geometry mode at runtime?
  3836. #define RUNTIME_GEOMETRY_MODE
  3837. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  3838. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  3839. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  3840. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  3841. // PHOSPHOR MASK:
  3842. // Manually resize the phosphor mask for best results (slower)? Disabling this
  3843. // removes the option to do so, but it may be faster without dynamic branches.
  3844. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  3845. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  3846. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  3847. // Larger blurs are expensive, but we need them to blur larger triads. We can
  3848. // detect the right blur if the triad size is static or our profile allows
  3849. // dynamic branches, but otherwise we use the largest blur the user indicates
  3850. // they might need:
  3851. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  3852. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  3853. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  3854. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  3855. // Here's a helpful chart:
  3856. // MaxTriadSize BlurSize MinTriadCountsByResolution
  3857. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3858. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3859. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3860. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3861. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  3862. /////////////////////////////// USER PARAMETERS //////////////////////////////
  3863. // Note: Many of these static parameters are overridden by runtime shader
  3864. // parameters when those are enabled. However, many others are static codepath
  3865. // options that were cleaner or more convert to code as static constants.
  3866. // GAMMA:
  3867. static const float crt_gamma_static = 2.5; // range [1, 5]
  3868. static const float lcd_gamma_static = 2.2; // range [1, 5]
  3869. // LEVELS MANAGEMENT:
  3870. // Control the final multiplicative image contrast:
  3871. static const float levels_contrast_static = 1.0; // range [0, 4)
  3872. // We auto-dim to avoid clipping between passes and restore brightness
  3873. // later. Control the dim factor here: Lower values clip less but crush
  3874. // blacks more (static only for now).
  3875. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  3876. // HALATION/DIFFUSION/BLOOM:
  3877. // Halation weight: How much energy should be lost to electrons bounding
  3878. // around under the CRT glass and exciting random phosphors?
  3879. static const float halation_weight_static = 0.0; // range [0, 1]
  3880. // Refractive diffusion weight: How much light should spread/diffuse from
  3881. // refracting through the CRT glass?
  3882. static const float diffusion_weight_static = 0.075; // range [0, 1]
  3883. // Underestimate brightness: Bright areas bloom more, but we can base the
  3884. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  3885. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  3886. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  3887. // Blur all colors more than necessary for a softer phosphor bloom?
  3888. static const float bloom_excess_static = 0.0; // range [0, 1]
  3889. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  3890. // blurred resize of the input (convergence offsets are applied as well).
  3891. // There are three filter options (static option only for now):
  3892. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  3893. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  3894. // and beam_max_sigma is low.
  3895. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  3896. // always uses a static sigma regardless of beam_max_sigma or
  3897. // mask_num_triads_desired.
  3898. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  3899. // These options are more pronounced for the fast, unbloomed shader version.
  3900. #ifndef RADEON_FIX
  3901. static const float bloom_approx_filter_static = 2.0;
  3902. #else
  3903. static const float bloom_approx_filter_static = 1.0;
  3904. #endif
  3905. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  3906. // How many scanlines should contribute light to each pixel? Using more
  3907. // scanlines is slower (especially for a generalized Gaussian) but less
  3908. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  3909. // max_beam_sigma at which the closest unused weight is guaranteed <
  3910. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  3911. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  3912. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  3913. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  3914. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  3915. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  3916. static const float beam_num_scanlines = 3.0; // range [2, 6]
  3917. // A generalized Gaussian beam varies shape with color too, now just width.
  3918. // It's slower but more flexible (static option only for now).
  3919. static const bool beam_generalized_gaussian = true;
  3920. // What kind of scanline antialiasing do you want?
  3921. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  3922. // Integrals are slow (especially for generalized Gaussians) and rarely any
  3923. // better than 3x antialiasing (static option only for now).
  3924. static const float beam_antialias_level = 1.0; // range [0, 2]
  3925. // Min/max standard deviations for scanline beams: Higher values widen and
  3926. // soften scanlines. Depending on other options, low min sigmas can alias.
  3927. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  3928. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  3929. // Beam width varies as a function of color: A power function (0) is more
  3930. // configurable, but a spherical function (1) gives the widest beam
  3931. // variability without aliasing (static option only for now).
  3932. static const float beam_spot_shape_function = 0.0;
  3933. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  3934. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  3935. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  3936. // Generalized Gaussian max shape parameters: Higher values give flatter
  3937. // scanline plateaus and steeper dropoffs, simultaneously widening and
  3938. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  3939. // values > ~40.0 cause artifacts with integrals.
  3940. static const float beam_min_shape_static = 2.0; // range [2, 32]
  3941. static const float beam_max_shape_static = 4.0; // range [2, 32]
  3942. // Generalized Gaussian shape power: Affects how quickly the distribution
  3943. // changes shape from Gaussian to steep/plateaued as color increases from 0
  3944. // to 1.0. Higher powers appear softer for most colors, and lower powers
  3945. // appear sharper for most colors.
  3946. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  3947. // What filter should be used to sample scanlines horizontally?
  3948. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  3949. static const float beam_horiz_filter_static = 0.0;
  3950. // Standard deviation for horizontal Gaussian resampling:
  3951. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  3952. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  3953. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  3954. // limiting circuitry in some CRT's), or a weighted avg.?
  3955. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  3956. // Simulate scanline misconvergence? This needs 3x horizontal texture
  3957. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  3958. // later passes (static option only for now).
  3959. static const bool beam_misconvergence = true;
  3960. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  3961. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  3962. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  3963. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  3964. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  3965. // Detect interlacing (static option only for now)?
  3966. static const bool interlace_detect = true;
  3967. // Assume 1080-line sources are interlaced?
  3968. static const bool interlace_1080i_static = false;
  3969. // For interlaced sources, assume TFF (top-field first) or BFF order?
  3970. // (Whether this matters depends on the nature of the interlaced input.)
  3971. static const bool interlace_bff_static = false;
  3972. // ANTIALIASING:
  3973. // What AA level do you want for curvature/overscan/subpixels? Options:
  3974. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  3975. // (Static option only for now)
  3976. static const float aa_level = 12.0; // range [0, 24]
  3977. // What antialiasing filter do you want (static option only)? Options:
  3978. // 0: Box (separable), 1: Box (cylindrical),
  3979. // 2: Tent (separable), 3: Tent (cylindrical),
  3980. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  3981. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  3982. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  3983. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  3984. static const float aa_filter = 6.0; // range [0, 9]
  3985. // Flip the sample grid on odd/even frames (static option only for now)?
  3986. static const bool aa_temporal = false;
  3987. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  3988. // the blue offset is the negative r offset; range [0, 0.5]
  3989. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  3990. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  3991. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  3992. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  3993. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  3994. // 4.) C = 0.0 is a soft spline filter.
  3995. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  3996. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  3997. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  3998. // PHOSPHOR MASK:
  3999. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  4000. static const float mask_type_static = 1.0; // range [0, 2]
  4001. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  4002. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  4003. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  4004. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  4005. // is halfway decent with LUT mipmapping but atrocious without it.
  4006. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  4007. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  4008. // This mode reuses the same masks, so triads will be enormous unless
  4009. // you change the mask LUT filenames in your .cgp file.
  4010. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  4011. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  4012. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  4013. // will always be used to calculate the full bloom sigma statically.
  4014. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  4015. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  4016. // triads) will be rounded to the nearest integer tile size and clamped to
  4017. // obey minimum size constraints (imposed to reduce downsize taps) and
  4018. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  4019. // To increase the size limit, double the viewport-relative scales for the
  4020. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  4021. // range [1, mask_texture_small_size/mask_triads_per_tile]
  4022. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  4023. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  4024. // final size will be rounded and constrained as above); default 480.0
  4025. static const float mask_num_triads_desired_static = 480.0;
  4026. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  4027. // more samples and avoid moire a bit better, but some is unavoidable
  4028. // depending on the destination size (static option for now).
  4029. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  4030. // The mask is resized using a variable number of taps in each dimension,
  4031. // but some Cg profiles always fetch a constant number of taps no matter
  4032. // what (no dynamic branching). We can limit the maximum number of taps if
  4033. // we statically limit the minimum phosphor triad size. Larger values are
  4034. // faster, but the limit IS enforced (static option only, forever);
  4035. // range [1, mask_texture_small_size/mask_triads_per_tile]
  4036. // TODO: Make this 1.0 and compensate with smarter sampling!
  4037. static const float mask_min_allowed_triad_size = 2.0;
  4038. // GEOMETRY:
  4039. // Geometry mode:
  4040. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  4041. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  4042. static const float geom_mode_static = 0.0; // range [0, 3]
  4043. // Radius of curvature: Measured in units of your viewport's diagonal size.
  4044. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  4045. // View dist is the distance from the player to their physical screen, in
  4046. // units of the viewport's diagonal size. It controls the field of view.
  4047. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  4048. // Tilt angle in radians (clockwise around up and right vectors):
  4049. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  4050. // Aspect ratio: When the true viewport size is unknown, this value is used
  4051. // to help convert between the phosphor triad size and count, along with
  4052. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  4053. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  4054. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  4055. // default (256/224)*(54/47) = 1.313069909 (see below)
  4056. static const float geom_aspect_ratio_static = 1.313069909;
  4057. // Before getting into overscan, here's some general aspect ratio info:
  4058. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  4059. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  4060. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  4061. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  4062. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  4063. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  4064. // a.) Enable Retroarch's "Crop Overscan"
  4065. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  4066. // Real consoles use horizontal black padding in the signal, but emulators
  4067. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  4068. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  4069. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  4070. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  4071. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  4072. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  4073. // without doing a. or b., but horizontal image borders will be tighter
  4074. // than vertical ones, messing up curvature and overscan. Fixing the
  4075. // padding first corrects this.
  4076. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  4077. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  4078. // above: Values < 1.0 zoom out; range (0, inf)
  4079. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  4080. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  4081. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  4082. // with strong curvature (static option only for now).
  4083. static const bool geom_force_correct_tangent_matrix = true;
  4084. // BORDERS:
  4085. // Rounded border size in texture uv coords:
  4086. static const float border_size_static = 0.015; // range [0, 0.5]
  4087. // Border darkness: Moderate values darken the border smoothly, and high
  4088. // values make the image very dark just inside the border:
  4089. static const float border_darkness_static = 2.0; // range [0, inf)
  4090. // Border compression: High numbers compress border transitions, narrowing
  4091. // the dark border area.
  4092. static const float border_compress_static = 2.5; // range [1, inf)
  4093. #endif // USER_SETTINGS_H
  4094. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  4095. //#include "user-cgp-constants.h"
  4096. ///////////////////////// BEGIN USER-CGP-CONSTANTS /////////////////////////
  4097. #ifndef USER_CGP_CONSTANTS_H
  4098. #define USER_CGP_CONSTANTS_H
  4099. // IMPORTANT:
  4100. // These constants MUST be set appropriately for the settings in crt-royale.cgp
  4101. // (or whatever related .cgp file you're using). If they aren't, you're likely
  4102. // to get artifacts, the wrong phosphor mask size, etc. I wish these could be
  4103. // set directly in the .cgp file to make things easier, but...they can't.
  4104. // PASS SCALES AND RELATED CONSTANTS:
  4105. // Copy the absolute scale_x for BLOOM_APPROX. There are two major versions of
  4106. // this shader: One does a viewport-scale bloom, and the other skips it. The
  4107. // latter benefits from a higher bloom_approx_scale_x, so save both separately:
  4108. static const float bloom_approx_size_x = 320.0;
  4109. static const float bloom_approx_size_x_for_fake = 400.0;
  4110. // Copy the viewport-relative scales of the phosphor mask resize passes
  4111. // (MASK_RESIZE and the pass immediately preceding it):
  4112. static const float2 mask_resize_viewport_scale = float2(0.0625, 0.0625);
  4113. // Copy the geom_max_aspect_ratio used to calculate the MASK_RESIZE scales, etc.:
  4114. static const float geom_max_aspect_ratio = 4.0/3.0;
  4115. // PHOSPHOR MASK TEXTURE CONSTANTS:
  4116. // Set the following constants to reflect the properties of the phosphor mask
  4117. // texture named in crt-royale.cgp. The shader optionally resizes a mask tile
  4118. // based on user settings, then repeats a single tile until filling the screen.
  4119. // The shader must know the input texture size (default 64x64), and to manually
  4120. // resize, it must also know the horizontal triads per tile (default 8).
  4121. static const float2 mask_texture_small_size = float2(64.0, 64.0);
  4122. static const float2 mask_texture_large_size = float2(512.0, 512.0);
  4123. static const float mask_triads_per_tile = 8.0;
  4124. // We need the average brightness of the phosphor mask to compensate for the
  4125. // dimming it causes. The following four values are roughly correct for the
  4126. // masks included with the shader. Update the value for any LUT texture you
  4127. // change. [Un]comment "#define PHOSPHOR_MASK_GRILLE14" depending on whether
  4128. // the loaded aperture grille uses 14-pixel or 15-pixel stripes (default 15).
  4129. //#define PHOSPHOR_MASK_GRILLE14
  4130. static const float mask_grille14_avg_color = 50.6666666/255.0;
  4131. // TileableLinearApertureGrille14Wide7d33Spacing*.png
  4132. // TileableLinearApertureGrille14Wide10And6Spacing*.png
  4133. static const float mask_grille15_avg_color = 53.0/255.0;
  4134. // TileableLinearApertureGrille15Wide6d33Spacing*.png
  4135. // TileableLinearApertureGrille15Wide8And5d5Spacing*.png
  4136. static const float mask_slot_avg_color = 46.0/255.0;
  4137. // TileableLinearSlotMask15Wide9And4d5Horizontal8VerticalSpacing*.png
  4138. // TileableLinearSlotMaskTall15Wide9And4d5Horizontal9d14VerticalSpacing*.png
  4139. static const float mask_shadow_avg_color = 41.0/255.0;
  4140. // TileableLinearShadowMask*.png
  4141. // TileableLinearShadowMaskEDP*.png
  4142. #ifdef PHOSPHOR_MASK_GRILLE14
  4143. static const float mask_grille_avg_color = mask_grille14_avg_color;
  4144. #else
  4145. static const float mask_grille_avg_color = mask_grille15_avg_color;
  4146. #endif
  4147. #endif // USER_CGP_CONSTANTS_H
  4148. ////////////////////////// END USER-CGP-CONSTANTS //////////////////////////
  4149. //////////////////////////////// END INCLUDES ////////////////////////////////
  4150. /////////////////////////////// FIXED SETTINGS ///////////////////////////////
  4151. // Avoid dividing by zero; using a macro overloads for float, float2, etc.:
  4152. #define FIX_ZERO(c) (max(abs(c), 0.0000152587890625)) // 2^-16
  4153. // Ensure the first pass decodes CRT gamma and the last encodes LCD gamma.
  4154. #ifndef SIMULATE_CRT_ON_LCD
  4155. #define SIMULATE_CRT_ON_LCD
  4156. #endif
  4157. // Manually tiling a manually resized texture creates texture coord derivative
  4158. // discontinuities and confuses anisotropic filtering, causing discolored tile
  4159. // seams in the phosphor mask. Workarounds:
  4160. // a.) Using tex2Dlod disables anisotropic filtering for tiled masks. It's
  4161. // downgraded to tex2Dbias without DRIVERS_ALLOW_TEX2DLOD #defined and
  4162. // disabled without DRIVERS_ALLOW_TEX2DBIAS #defined either.
  4163. // b.) "Tile flat twice" requires drawing two full tiles without border padding
  4164. // to the resized mask FBO, and it's incompatible with same-pass curvature.
  4165. // (Same-pass curvature isn't used but could be in the future...maybe.)
  4166. // c.) "Fix discontinuities" requires derivatives and drawing one tile with
  4167. // border padding to the resized mask FBO, but it works with same-pass
  4168. // curvature. It's disabled without DRIVERS_ALLOW_DERIVATIVES #defined.
  4169. // Precedence: a, then, b, then c (if multiple strategies are #defined).
  4170. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD // 129.7 FPS, 4x, flat; 101.8 at fullscreen
  4171. #define ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE // 128.1 FPS, 4x, flat; 101.5 at fullscreen
  4172. #define ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES // 124.4 FPS, 4x, flat; 97.4 at fullscreen
  4173. // Also, manually resampling the phosphor mask is slightly blurrier with
  4174. // anisotropic filtering. (Resampling with mipmapping is even worse: It
  4175. // creates artifacts, but only with the fully bloomed shader.) The difference
  4176. // is subtle with small triads, but you can fix it for a small cost.
  4177. //#define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4178. ////////////////////////////// DERIVED SETTINGS //////////////////////////////
  4179. // Intel HD 4000 GPU's can't handle manual mask resizing (for now), setting the
  4180. // geometry mode at runtime, or a 4x4 true Gaussian resize. Disable
  4181. // incompatible settings ASAP. (INTEGRATED_GRAPHICS_COMPATIBILITY_MODE may be
  4182. // #defined by either user-settings.h or a wrapper .cg that #includes the
  4183. // current .cg pass.)
  4184. #ifdef INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  4185. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  4186. #undef PHOSPHOR_MASK_MANUALLY_RESIZE
  4187. #endif
  4188. #ifdef RUNTIME_GEOMETRY_MODE
  4189. #undef RUNTIME_GEOMETRY_MODE
  4190. #endif
  4191. // Mode 2 (4x4 Gaussian resize) won't work, and mode 1 (3x3 blur) is
  4192. // inferior in most cases, so replace 2.0 with 0.0:
  4193. static const float bloom_approx_filter =
  4194. bloom_approx_filter_static > 1.5 ? 0.0 : bloom_approx_filter_static;
  4195. #else
  4196. static const float bloom_approx_filter = bloom_approx_filter_static;
  4197. #endif
  4198. // Disable slow runtime paths if static parameters are used. Most of these
  4199. // won't be a problem anyway once the params are disabled, but some will.
  4200. #ifndef RUNTIME_SHADER_PARAMS_ENABLE
  4201. #ifdef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  4202. #undef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  4203. #endif
  4204. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  4205. #undef RUNTIME_ANTIALIAS_WEIGHTS
  4206. #endif
  4207. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  4208. #undef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  4209. #endif
  4210. #ifdef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  4211. #undef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  4212. #endif
  4213. #ifdef RUNTIME_GEOMETRY_TILT
  4214. #undef RUNTIME_GEOMETRY_TILT
  4215. #endif
  4216. #ifdef RUNTIME_GEOMETRY_MODE
  4217. #undef RUNTIME_GEOMETRY_MODE
  4218. #endif
  4219. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  4220. #undef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  4221. #endif
  4222. #endif
  4223. // Make tex2Dbias a backup for tex2Dlod for wider compatibility.
  4224. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  4225. #define ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4226. #endif
  4227. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4228. #define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  4229. #endif
  4230. // Rule out unavailable anisotropic compatibility strategies:
  4231. #ifndef DRIVERS_ALLOW_DERIVATIVES
  4232. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4233. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4234. #endif
  4235. #endif
  4236. #ifndef DRIVERS_ALLOW_TEX2DLOD
  4237. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  4238. #undef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  4239. #endif
  4240. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4241. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4242. #endif
  4243. #ifdef ANTIALIAS_DISABLE_ANISOTROPIC
  4244. #undef ANTIALIAS_DISABLE_ANISOTROPIC
  4245. #endif
  4246. #endif
  4247. #ifndef DRIVERS_ALLOW_TEX2DBIAS
  4248. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4249. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4250. #endif
  4251. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  4252. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  4253. #endif
  4254. #endif
  4255. // Prioritize anisotropic tiling compatibility strategies by performance and
  4256. // disable unused strategies. This concentrates all the nesting in one place.
  4257. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  4258. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4259. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4260. #endif
  4261. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4262. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4263. #endif
  4264. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4265. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4266. #endif
  4267. #else
  4268. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4269. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4270. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4271. #endif
  4272. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4273. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4274. #endif
  4275. #else
  4276. // ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE is only compatible with
  4277. // flat texture coords in the same pass, but that's all we use.
  4278. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4279. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4280. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4281. #endif
  4282. #endif
  4283. #endif
  4284. #endif
  4285. // The tex2Dlod and tex2Dbias strategies share a lot in common, and we can
  4286. // reduce some #ifdef nesting in the next section by essentially OR'ing them:
  4287. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  4288. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  4289. #endif
  4290. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  4291. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  4292. #endif
  4293. // Prioritize anisotropic resampling compatibility strategies the same way:
  4294. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4295. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  4296. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  4297. #endif
  4298. #endif
  4299. /////////////////////// DERIVED PHOSPHOR MASK CONSTANTS //////////////////////
  4300. // If we can use the large mipmapped LUT without mipmapping artifacts, we
  4301. // should: It gives us more options for using fewer samples.
  4302. #ifdef DRIVERS_ALLOW_TEX2DLOD
  4303. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  4304. // TODO: Take advantage of this!
  4305. #define PHOSPHOR_MASK_RESIZE_MIPMAPPED_LUT
  4306. static const float2 mask_resize_src_lut_size = mask_texture_large_size;
  4307. #else
  4308. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  4309. #endif
  4310. #else
  4311. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  4312. #endif
  4313. // tex2D's sampler2D parameter MUST be a uniform global, a uniform input to
  4314. // main_fragment, or a static alias of one of the above. This makes it hard
  4315. // to select the phosphor mask at runtime: We can't even assign to a uniform
  4316. // global in the vertex shader or select a sampler2D in the vertex shader and
  4317. // pass it to the fragment shader (even with explicit TEXUNIT# bindings),
  4318. // because it just gives us the input texture or a black screen. However, we
  4319. // can get around these limitations by calling tex2D three times with different
  4320. // uniform samplers (or resizing the phosphor mask three times altogether).
  4321. // With dynamic branches, we can process only one of these branches on top of
  4322. // quickly discarding fragments we don't need (cgc seems able to overcome
  4323. // limigations around dependent texture fetches inside of branches). Without
  4324. // dynamic branches, we have to process every branch for every fragment...which
  4325. // is slower. Runtime sampling mode selection is slower without dynamic
  4326. // branches as well. Let the user's static #defines decide if it's worth it.
  4327. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  4328. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  4329. #else
  4330. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  4331. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  4332. #endif
  4333. #endif
  4334. // We need to render some minimum number of tiles in the resize passes.
  4335. // We need at least 1.0 just to repeat a single tile, and we need extra
  4336. // padding beyond that for anisotropic filtering, discontinuitity fixing,
  4337. // antialiasing, same-pass curvature (not currently used), etc. First
  4338. // determine how many border texels and tiles we need, based on how the result
  4339. // will be sampled:
  4340. #ifdef GEOMETRY_EARLY
  4341. static const float max_subpixel_offset = aa_subpixel_r_offset_static.x;
  4342. // Most antialiasing filters have a base radius of 4.0 pixels:
  4343. static const float max_aa_base_pixel_border = 4.0 +
  4344. max_subpixel_offset;
  4345. #else
  4346. static const float max_aa_base_pixel_border = 0.0;
  4347. #endif
  4348. // Anisotropic filtering adds about 0.5 to the pixel border:
  4349. #ifndef ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  4350. static const float max_aniso_pixel_border = max_aa_base_pixel_border + 0.5;
  4351. #else
  4352. static const float max_aniso_pixel_border = max_aa_base_pixel_border;
  4353. #endif
  4354. // Fixing discontinuities adds 1.0 more to the pixel border:
  4355. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  4356. static const float max_tiled_pixel_border = max_aniso_pixel_border + 1.0;
  4357. #else
  4358. static const float max_tiled_pixel_border = max_aniso_pixel_border;
  4359. #endif
  4360. // Convert the pixel border to an integer texel border. Assume same-pass
  4361. // curvature about triples the texel frequency:
  4362. #ifdef GEOMETRY_EARLY
  4363. static const float max_mask_texel_border =
  4364. ceil(max_tiled_pixel_border * 3.0);
  4365. #else
  4366. static const float max_mask_texel_border = ceil(max_tiled_pixel_border);
  4367. #endif
  4368. // Convert the texel border to a tile border using worst-case assumptions:
  4369. static const float max_mask_tile_border = max_mask_texel_border/
  4370. (mask_min_allowed_triad_size * mask_triads_per_tile);
  4371. // Finally, set the number of resized tiles to render to MASK_RESIZE, and set
  4372. // the starting texel (inside borders) for sampling it.
  4373. #ifndef GEOMETRY_EARLY
  4374. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  4375. // Special case: Render two tiles without borders. Anisotropic
  4376. // filtering doesn't seem to be a problem here.
  4377. static const float mask_resize_num_tiles = 1.0 + 1.0;
  4378. static const float mask_start_texels = 0.0;
  4379. #else
  4380. static const float mask_resize_num_tiles = 1.0 +
  4381. 2.0 * max_mask_tile_border;
  4382. static const float mask_start_texels = max_mask_texel_border;
  4383. #endif
  4384. #else
  4385. static const float mask_resize_num_tiles = 1.0 + 2.0*max_mask_tile_border;
  4386. static const float mask_start_texels = max_mask_texel_border;
  4387. #endif
  4388. // We have to fit mask_resize_num_tiles into an FBO with a viewport scale of
  4389. // mask_resize_viewport_scale. This limits the maximum final triad size.
  4390. // Estimate the minimum number of triads we can split the screen into in each
  4391. // dimension (we'll be as correct as mask_resize_viewport_scale is):
  4392. static const float mask_resize_num_triads =
  4393. mask_resize_num_tiles * mask_triads_per_tile;
  4394. static const float2 min_allowed_viewport_triads =
  4395. float2(mask_resize_num_triads) / mask_resize_viewport_scale;
  4396. //////////////////////// COMMON MATHEMATICAL CONSTANTS ///////////////////////
  4397. static const float pi = 3.141592653589;
  4398. // We often want to find the location of the previous texel, e.g.:
  4399. // const float2 curr_texel = uv * texture_size;
  4400. // const float2 prev_texel = floor(curr_texel - float2(0.5)) + float2(0.5);
  4401. // const float2 prev_texel_uv = prev_texel / texture_size;
  4402. // However, many GPU drivers round incorrectly around exact texel locations.
  4403. // We need to subtract a little less than 0.5 before flooring, and some GPU's
  4404. // require this value to be farther from 0.5 than others; define it here.
  4405. // const float2 prev_texel =
  4406. // floor(curr_texel - float2(under_half)) + float2(0.5);
  4407. static const float under_half = 0.4995;
  4408. #endif // DERIVED_SETTINGS_AND_CONSTANTS_H
  4409. ///////////////////////////// END DERIVED-SETTINGS-AND-CONSTANTS ////////////////////////////
  4410. //#include "../../../../include/special-functions.h"
  4411. /////////////////////////// BEGIN SPECIAL-FUNCTIONS //////////////////////////
  4412. #ifndef SPECIAL_FUNCTIONS_H
  4413. #define SPECIAL_FUNCTIONS_H
  4414. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  4415. // Copyright (C) 2014 TroggleMonkey
  4416. //
  4417. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4418. // of this software and associated documentation files (the "Software"), to
  4419. // deal in the Software without restriction, including without limitation the
  4420. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  4421. // sell copies of the Software, and to permit persons to whom the Software is
  4422. // furnished to do so, subject to the following conditions:
  4423. //
  4424. // The above copyright notice and this permission notice shall be included in
  4425. // all copies or substantial portions of the Software.
  4426. //
  4427. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4428. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4429. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4430. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4431. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  4432. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  4433. // IN THE SOFTWARE.
  4434. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  4435. // This file implements the following mathematical special functions:
  4436. // 1.) erf() = 2/sqrt(pi) * indefinite_integral(e**(-x**2))
  4437. // 2.) gamma(s), a real-numbered extension of the integer factorial function
  4438. // It also implements normalized_ligamma(s, z), a normalized lower incomplete
  4439. // gamma function for s < 0.5 only. Both gamma() and normalized_ligamma() can
  4440. // be called with an _impl suffix to use an implementation version with a few
  4441. // extra precomputed parameters (which may be useful for the caller to reuse).
  4442. // See below for details.
  4443. //
  4444. // Design Rationale:
  4445. // Pretty much every line of code in this file is duplicated four times for
  4446. // different input types (float4/float3/float2/float). This is unfortunate,
  4447. // but Cg doesn't allow function templates. Macros would be far less verbose,
  4448. // but they would make the code harder to document and read. I don't expect
  4449. // these functions will require a whole lot of maintenance changes unless
  4450. // someone ever has need for more robust incomplete gamma functions, so code
  4451. // duplication seems to be the lesser evil in this case.
  4452. /////////////////////////// GAUSSIAN ERROR FUNCTION //////////////////////////
  4453. float4 erf6(float4 x)
  4454. {
  4455. // Requires: x is the standard parameter to erf().
  4456. // Returns: Return an Abramowitz/Stegun approximation of erf(), where:
  4457. // erf(x) = 2/sqrt(pi) * integral(e**(-x**2))
  4458. // This approximation has a max absolute error of 2.5*10**-5
  4459. // with solid numerical robustness and efficiency. See:
  4460. // https://en.wikipedia.org/wiki/Error_function#Approximation_with_elementary_functions
  4461. static const float4 one = float4(1.0);
  4462. const float4 sign_x = sign(x);
  4463. const float4 t = one/(one + 0.47047*abs(x));
  4464. const float4 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  4465. exp(-(x*x));
  4466. return result * sign_x;
  4467. }
  4468. float3 erf6(const float3 x)
  4469. {
  4470. // Float3 version:
  4471. static const float3 one = float3(1.0);
  4472. const float3 sign_x = sign(x);
  4473. const float3 t = one/(one + 0.47047*abs(x));
  4474. const float3 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  4475. exp(-(x*x));
  4476. return result * sign_x;
  4477. }
  4478. float2 erf6(const float2 x)
  4479. {
  4480. // Float2 version:
  4481. static const float2 one = float2(1.0);
  4482. const float2 sign_x = sign(x);
  4483. const float2 t = one/(one + 0.47047*abs(x));
  4484. const float2 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  4485. exp(-(x*x));
  4486. return result * sign_x;
  4487. }
  4488. float erf6(const float x)
  4489. {
  4490. // Float version:
  4491. const float sign_x = sign(x);
  4492. const float t = 1.0/(1.0 + 0.47047*abs(x));
  4493. const float result = 1.0 - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  4494. exp(-(x*x));
  4495. return result * sign_x;
  4496. }
  4497. float4 erft(const float4 x)
  4498. {
  4499. // Requires: x is the standard parameter to erf().
  4500. // Returns: Approximate erf() with the hyperbolic tangent. The error is
  4501. // visually noticeable, but it's blazing fast and perceptually
  4502. // close...at least on ATI hardware. See:
  4503. // http://www.maplesoft.com/applications/view.aspx?SID=5525&view=html
  4504. // Warning: Only use this if your hardware drivers correctly implement
  4505. // tanh(): My nVidia 8800GTS returns garbage output.
  4506. return tanh(1.202760580 * x);
  4507. }
  4508. float3 erft(const float3 x)
  4509. {
  4510. // Float3 version:
  4511. return tanh(1.202760580 * x);
  4512. }
  4513. float2 erft(const float2 x)
  4514. {
  4515. // Float2 version:
  4516. return tanh(1.202760580 * x);
  4517. }
  4518. float erft(const float x)
  4519. {
  4520. // Float version:
  4521. return tanh(1.202760580 * x);
  4522. }
  4523. inline float4 erf(const float4 x)
  4524. {
  4525. // Requires: x is the standard parameter to erf().
  4526. // Returns: Some approximation of erf(x), depending on user settings.
  4527. #ifdef ERF_FAST_APPROXIMATION
  4528. return erft(x);
  4529. #else
  4530. return erf6(x);
  4531. #endif
  4532. }
  4533. inline float3 erf(const float3 x)
  4534. {
  4535. // Float3 version:
  4536. #ifdef ERF_FAST_APPROXIMATION
  4537. return erft(x);
  4538. #else
  4539. return erf6(x);
  4540. #endif
  4541. }
  4542. inline float2 erf(const float2 x)
  4543. {
  4544. // Float2 version:
  4545. #ifdef ERF_FAST_APPROXIMATION
  4546. return erft(x);
  4547. #else
  4548. return erf6(x);
  4549. #endif
  4550. }
  4551. inline float erf(const float x)
  4552. {
  4553. // Float version:
  4554. #ifdef ERF_FAST_APPROXIMATION
  4555. return erft(x);
  4556. #else
  4557. return erf6(x);
  4558. #endif
  4559. }
  4560. /////////////////////////// COMPLETE GAMMA FUNCTION //////////////////////////
  4561. float4 gamma_impl(const float4 s, const float4 s_inv)
  4562. {
  4563. // Requires: 1.) s is the standard parameter to the gamma function, and
  4564. // it should lie in the [0, 36] range.
  4565. // 2.) s_inv = 1.0/s. This implementation function requires
  4566. // the caller to precompute this value, giving users the
  4567. // opportunity to reuse it.
  4568. // Returns: Return approximate gamma function (real-numbered factorial)
  4569. // output using the Lanczos approximation with two coefficients
  4570. // calculated using Paul Godfrey's method here:
  4571. // http://my.fit.edu/~gabdo/gamma.txt
  4572. // An optimal g value for s in [0, 36] is ~1.12906830989, with
  4573. // a maximum relative error of 0.000463 for 2**16 equally
  4574. // evals. We could use three coeffs (0.0000346 error) without
  4575. // hurting latency, but this allows more parallelism with
  4576. // outside instructions.
  4577. static const float4 g = float4(1.12906830989);
  4578. static const float4 c0 = float4(0.8109119309638332633713423362694399653724431);
  4579. static const float4 c1 = float4(0.4808354605142681877121661197951496120000040);
  4580. static const float4 e = float4(2.71828182845904523536028747135266249775724709);
  4581. const float4 sph = s + float4(0.5);
  4582. const float4 lanczos_sum = c0 + c1/(s + float4(1.0));
  4583. const float4 base = (sph + g)/e; // or (s + g + float4(0.5))/e
  4584. // gamma(s + 1) = base**sph * lanczos_sum; divide by s for gamma(s).
  4585. // This has less error for small s's than (s -= 1.0) at the beginning.
  4586. return (pow(base, sph) * lanczos_sum) * s_inv;
  4587. }
  4588. float3 gamma_impl(const float3 s, const float3 s_inv)
  4589. {
  4590. // Float3 version:
  4591. static const float3 g = float3(1.12906830989);
  4592. static const float3 c0 = float3(0.8109119309638332633713423362694399653724431);
  4593. static const float3 c1 = float3(0.4808354605142681877121661197951496120000040);
  4594. static const float3 e = float3(2.71828182845904523536028747135266249775724709);
  4595. const float3 sph = s + float3(0.5);
  4596. const float3 lanczos_sum = c0 + c1/(s + float3(1.0));
  4597. const float3 base = (sph + g)/e;
  4598. return (pow(base, sph) * lanczos_sum) * s_inv;
  4599. }
  4600. float2 gamma_impl(const float2 s, const float2 s_inv)
  4601. {
  4602. // Float2 version:
  4603. static const float2 g = float2(1.12906830989);
  4604. static const float2 c0 = float2(0.8109119309638332633713423362694399653724431);
  4605. static const float2 c1 = float2(0.4808354605142681877121661197951496120000040);
  4606. static const float2 e = float2(2.71828182845904523536028747135266249775724709);
  4607. const float2 sph = s + float2(0.5);
  4608. const float2 lanczos_sum = c0 + c1/(s + float2(1.0));
  4609. const float2 base = (sph + g)/e;
  4610. return (pow(base, sph) * lanczos_sum) * s_inv;
  4611. }
  4612. float gamma_impl(const float s, const float s_inv)
  4613. {
  4614. // Float version:
  4615. static const float g = 1.12906830989;
  4616. static const float c0 = 0.8109119309638332633713423362694399653724431;
  4617. static const float c1 = 0.4808354605142681877121661197951496120000040;
  4618. static const float e = 2.71828182845904523536028747135266249775724709;
  4619. const float sph = s + 0.5;
  4620. const float lanczos_sum = c0 + c1/(s + 1.0);
  4621. const float base = (sph + g)/e;
  4622. return (pow(base, sph) * lanczos_sum) * s_inv;
  4623. }
  4624. float4 gamma(const float4 s)
  4625. {
  4626. // Requires: s is the standard parameter to the gamma function, and it
  4627. // should lie in the [0, 36] range.
  4628. // Returns: Return approximate gamma function output with a maximum
  4629. // relative error of 0.000463. See gamma_impl for details.
  4630. return gamma_impl(s, float4(1.0)/s);
  4631. }
  4632. float3 gamma(const float3 s)
  4633. {
  4634. // Float3 version:
  4635. return gamma_impl(s, float3(1.0)/s);
  4636. }
  4637. float2 gamma(const float2 s)
  4638. {
  4639. // Float2 version:
  4640. return gamma_impl(s, float2(1.0)/s);
  4641. }
  4642. float gamma(const float s)
  4643. {
  4644. // Float version:
  4645. return gamma_impl(s, 1.0/s);
  4646. }
  4647. //////////////// INCOMPLETE GAMMA FUNCTIONS (RESTRICTED INPUT) ///////////////
  4648. // Lower incomplete gamma function for small s and z (implementation):
  4649. float4 ligamma_small_z_impl(const float4 s, const float4 z, const float4 s_inv)
  4650. {
  4651. // Requires: 1.) s < ~0.5
  4652. // 2.) z <= ~0.775075
  4653. // 3.) s_inv = 1.0/s (precomputed for outside reuse)
  4654. // Returns: A series representation for the lower incomplete gamma
  4655. // function for small s and small z (4 terms).
  4656. // The actual "rolled up" summation looks like:
  4657. // last_sign = 1.0; last_pow = 1.0; last_factorial = 1.0;
  4658. // sum = last_sign * last_pow / ((s + k) * last_factorial)
  4659. // for(int i = 0; i < 4; ++i)
  4660. // {
  4661. // last_sign *= -1.0; last_pow *= z; last_factorial *= i;
  4662. // sum += last_sign * last_pow / ((s + k) * last_factorial);
  4663. // }
  4664. // Unrolled, constant-unfolded and arranged for madds and parallelism:
  4665. const float4 scale = pow(z, s);
  4666. float4 sum = s_inv; // Summation iteration 0 result
  4667. // Summation iterations 1, 2, and 3:
  4668. const float4 z_sq = z*z;
  4669. const float4 denom1 = s + float4(1.0);
  4670. const float4 denom2 = 2.0*s + float4(4.0);
  4671. const float4 denom3 = 6.0*s + float4(18.0);
  4672. //float4 denom4 = 24.0*s + float4(96.0);
  4673. sum -= z/denom1;
  4674. sum += z_sq/denom2;
  4675. sum -= z * z_sq/denom3;
  4676. //sum += z_sq * z_sq / denom4;
  4677. // Scale and return:
  4678. return scale * sum;
  4679. }
  4680. float3 ligamma_small_z_impl(const float3 s, const float3 z, const float3 s_inv)
  4681. {
  4682. // Float3 version:
  4683. const float3 scale = pow(z, s);
  4684. float3 sum = s_inv;
  4685. const float3 z_sq = z*z;
  4686. const float3 denom1 = s + float3(1.0);
  4687. const float3 denom2 = 2.0*s + float3(4.0);
  4688. const float3 denom3 = 6.0*s + float3(18.0);
  4689. sum -= z/denom1;
  4690. sum += z_sq/denom2;
  4691. sum -= z * z_sq/denom3;
  4692. return scale * sum;
  4693. }
  4694. float2 ligamma_small_z_impl(const float2 s, const float2 z, const float2 s_inv)
  4695. {
  4696. // Float2 version:
  4697. const float2 scale = pow(z, s);
  4698. float2 sum = s_inv;
  4699. const float2 z_sq = z*z;
  4700. const float2 denom1 = s + float2(1.0);
  4701. const float2 denom2 = 2.0*s + float2(4.0);
  4702. const float2 denom3 = 6.0*s + float2(18.0);
  4703. sum -= z/denom1;
  4704. sum += z_sq/denom2;
  4705. sum -= z * z_sq/denom3;
  4706. return scale * sum;
  4707. }
  4708. float ligamma_small_z_impl(const float s, const float z, const float s_inv)
  4709. {
  4710. // Float version:
  4711. const float scale = pow(z, s);
  4712. float sum = s_inv;
  4713. const float z_sq = z*z;
  4714. const float denom1 = s + 1.0;
  4715. const float denom2 = 2.0*s + 4.0;
  4716. const float denom3 = 6.0*s + 18.0;
  4717. sum -= z/denom1;
  4718. sum += z_sq/denom2;
  4719. sum -= z * z_sq/denom3;
  4720. return scale * sum;
  4721. }
  4722. // Upper incomplete gamma function for small s and large z (implementation):
  4723. float4 uigamma_large_z_impl(const float4 s, const float4 z)
  4724. {
  4725. // Requires: 1.) s < ~0.5
  4726. // 2.) z > ~0.775075
  4727. // Returns: Gauss's continued fraction representation for the upper
  4728. // incomplete gamma function (4 terms).
  4729. // The "rolled up" continued fraction looks like this. The denominator
  4730. // is truncated, and it's calculated "from the bottom up:"
  4731. // denom = float4('inf');
  4732. // float4 one = float4(1.0);
  4733. // for(int i = 4; i > 0; --i)
  4734. // {
  4735. // denom = ((i * 2.0) - one) + z - s + (i * (s - i))/denom;
  4736. // }
  4737. // Unrolled and constant-unfolded for madds and parallelism:
  4738. const float4 numerator = pow(z, s) * exp(-z);
  4739. float4 denom = float4(7.0) + z - s;
  4740. denom = float4(5.0) + z - s + (3.0*s - float4(9.0))/denom;
  4741. denom = float4(3.0) + z - s + (2.0*s - float4(4.0))/denom;
  4742. denom = float4(1.0) + z - s + (s - float4(1.0))/denom;
  4743. return numerator / denom;
  4744. }
  4745. float3 uigamma_large_z_impl(const float3 s, const float3 z)
  4746. {
  4747. // Float3 version:
  4748. const float3 numerator = pow(z, s) * exp(-z);
  4749. float3 denom = float3(7.0) + z - s;
  4750. denom = float3(5.0) + z - s + (3.0*s - float3(9.0))/denom;
  4751. denom = float3(3.0) + z - s + (2.0*s - float3(4.0))/denom;
  4752. denom = float3(1.0) + z - s + (s - float3(1.0))/denom;
  4753. return numerator / denom;
  4754. }
  4755. float2 uigamma_large_z_impl(const float2 s, const float2 z)
  4756. {
  4757. // Float2 version:
  4758. const float2 numerator = pow(z, s) * exp(-z);
  4759. float2 denom = float2(7.0) + z - s;
  4760. denom = float2(5.0) + z - s + (3.0*s - float2(9.0))/denom;
  4761. denom = float2(3.0) + z - s + (2.0*s - float2(4.0))/denom;
  4762. denom = float2(1.0) + z - s + (s - float2(1.0))/denom;
  4763. return numerator / denom;
  4764. }
  4765. float uigamma_large_z_impl(const float s, const float z)
  4766. {
  4767. // Float version:
  4768. const float numerator = pow(z, s) * exp(-z);
  4769. float denom = 7.0 + z - s;
  4770. denom = 5.0 + z - s + (3.0*s - 9.0)/denom;
  4771. denom = 3.0 + z - s + (2.0*s - 4.0)/denom;
  4772. denom = 1.0 + z - s + (s - 1.0)/denom;
  4773. return numerator / denom;
  4774. }
  4775. // Normalized lower incomplete gamma function for small s (implementation):
  4776. float4 normalized_ligamma_impl(const float4 s, const float4 z,
  4777. const float4 s_inv, const float4 gamma_s_inv)
  4778. {
  4779. // Requires: 1.) s < ~0.5
  4780. // 2.) s_inv = 1/s (precomputed for outside reuse)
  4781. // 3.) gamma_s_inv = 1/gamma(s) (precomputed for outside reuse)
  4782. // Returns: Approximate the normalized lower incomplete gamma function
  4783. // for s < 0.5. Since we only care about s < 0.5, we only need
  4784. // to evaluate two branches (not four) based on z. Each branch
  4785. // uses four terms, with a max relative error of ~0.00182. The
  4786. // branch threshold and specifics were adapted for fewer terms
  4787. // from Gil/Segura/Temme's paper here:
  4788. // http://oai.cwi.nl/oai/asset/20433/20433B.pdf
  4789. // Evaluate both branches: Real branches test slower even when available.
  4790. static const float4 thresh = float4(0.775075);
  4791. bool4 z_is_large;
  4792. z_is_large.x = z.x > thresh.x;
  4793. z_is_large.y = z.y > thresh.y;
  4794. z_is_large.z = z.z > thresh.z;
  4795. z_is_large.w = z.w > thresh.w;
  4796. const float4 large_z = float4(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  4797. const float4 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  4798. // Combine the results from both branches:
  4799. bool4 inverse_z_is_large = not(z_is_large);
  4800. return large_z * float4(z_is_large) + small_z * float4(inverse_z_is_large);
  4801. }
  4802. float3 normalized_ligamma_impl(const float3 s, const float3 z,
  4803. const float3 s_inv, const float3 gamma_s_inv)
  4804. {
  4805. // Float3 version:
  4806. static const float3 thresh = float3(0.775075);
  4807. bool3 z_is_large;
  4808. z_is_large.x = z.x > thresh.x;
  4809. z_is_large.y = z.y > thresh.y;
  4810. z_is_large.z = z.z > thresh.z;
  4811. const float3 large_z = float3(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  4812. const float3 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  4813. bool3 inverse_z_is_large = not(z_is_large);
  4814. return large_z * float3(z_is_large) + small_z * float3(inverse_z_is_large);
  4815. }
  4816. float2 normalized_ligamma_impl(const float2 s, const float2 z,
  4817. const float2 s_inv, const float2 gamma_s_inv)
  4818. {
  4819. // Float2 version:
  4820. static const float2 thresh = float2(0.775075);
  4821. bool2 z_is_large;
  4822. z_is_large.x = z.x > thresh.x;
  4823. z_is_large.y = z.y > thresh.y;
  4824. const float2 large_z = float2(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  4825. const float2 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  4826. bool2 inverse_z_is_large = not(z_is_large);
  4827. return large_z * float2(z_is_large) + small_z * float2(inverse_z_is_large);
  4828. }
  4829. float normalized_ligamma_impl(const float s, const float z,
  4830. const float s_inv, const float gamma_s_inv)
  4831. {
  4832. // Float version:
  4833. static const float thresh = 0.775075;
  4834. const bool z_is_large = z > thresh;
  4835. const float large_z = 1.0 - uigamma_large_z_impl(s, z) * gamma_s_inv;
  4836. const float small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  4837. return large_z * float(z_is_large) + small_z * float(!z_is_large);
  4838. }
  4839. // Normalized lower incomplete gamma function for small s:
  4840. float4 normalized_ligamma(const float4 s, const float4 z)
  4841. {
  4842. // Requires: s < ~0.5
  4843. // Returns: Approximate the normalized lower incomplete gamma function
  4844. // for s < 0.5. See normalized_ligamma_impl() for details.
  4845. const float4 s_inv = float4(1.0)/s;
  4846. const float4 gamma_s_inv = float4(1.0)/gamma_impl(s, s_inv);
  4847. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  4848. }
  4849. float3 normalized_ligamma(const float3 s, const float3 z)
  4850. {
  4851. // Float3 version:
  4852. const float3 s_inv = float3(1.0)/s;
  4853. const float3 gamma_s_inv = float3(1.0)/gamma_impl(s, s_inv);
  4854. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  4855. }
  4856. float2 normalized_ligamma(const float2 s, const float2 z)
  4857. {
  4858. // Float2 version:
  4859. const float2 s_inv = float2(1.0)/s;
  4860. const float2 gamma_s_inv = float2(1.0)/gamma_impl(s, s_inv);
  4861. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  4862. }
  4863. float normalized_ligamma(const float s, const float z)
  4864. {
  4865. // Float version:
  4866. const float s_inv = 1.0/s;
  4867. const float gamma_s_inv = 1.0/gamma_impl(s, s_inv);
  4868. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  4869. }
  4870. #endif // SPECIAL_FUNCTIONS_H
  4871. //////////////////////////// END SPECIAL-FUNCTIONS ///////////////////////////
  4872. //#include "../../../../include/gamma-management.h"
  4873. //////////////////////////// BEGIN GAMMA-MANAGEMENT //////////////////////////
  4874. #ifndef GAMMA_MANAGEMENT_H
  4875. #define GAMMA_MANAGEMENT_H
  4876. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  4877. // Copyright (C) 2014 TroggleMonkey
  4878. //
  4879. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4880. // of this software and associated documentation files (the "Software"), to
  4881. // deal in the Software without restriction, including without limitation the
  4882. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  4883. // sell copies of the Software, and to permit persons to whom the Software is
  4884. // furnished to do so, subject to the following conditions:
  4885. //
  4886. // The above copyright notice and this permission notice shall be included in
  4887. // all copies or substantial portions of the Software.
  4888. //
  4889. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4890. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4891. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4892. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4893. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  4894. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  4895. // IN THE SOFTWARE.
  4896. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  4897. // This file provides gamma-aware tex*D*() and encode_output() functions.
  4898. // Requires: Before #include-ing this file, the including file must #define
  4899. // the following macros when applicable and follow their rules:
  4900. // 1.) #define FIRST_PASS if this is the first pass.
  4901. // 2.) #define LAST_PASS if this is the last pass.
  4902. // 3.) If sRGB is available, set srgb_framebufferN = "true" for
  4903. // every pass except the last in your .cgp preset.
  4904. // 4.) If sRGB isn't available but you want gamma-correctness with
  4905. // no banding, #define GAMMA_ENCODE_EVERY_FBO each pass.
  4906. // 5.) #define SIMULATE_CRT_ON_LCD if desired (precedence over 5-7)
  4907. // 6.) #define SIMULATE_GBA_ON_LCD if desired (precedence over 6-7)
  4908. // 7.) #define SIMULATE_LCD_ON_CRT if desired (precedence over 7)
  4909. // 8.) #define SIMULATE_GBA_ON_CRT if desired (precedence over -)
  4910. // If an option in [5, 8] is #defined in the first or last pass, it
  4911. // should be #defined for both. It shouldn't make a difference
  4912. // whether it's #defined for intermediate passes or not.
  4913. // Optional: The including file (or an earlier included file) may optionally
  4914. // #define a number of macros indicating it will override certain
  4915. // macros and associated constants are as follows:
  4916. // static constants with either static or uniform constants. The
  4917. // 1.) OVERRIDE_STANDARD_GAMMA: The user must first define:
  4918. // static const float ntsc_gamma
  4919. // static const float pal_gamma
  4920. // static const float crt_reference_gamma_high
  4921. // static const float crt_reference_gamma_low
  4922. // static const float lcd_reference_gamma
  4923. // static const float crt_office_gamma
  4924. // static const float lcd_office_gamma
  4925. // 2.) OVERRIDE_DEVICE_GAMMA: The user must first define:
  4926. // static const float crt_gamma
  4927. // static const float gba_gamma
  4928. // static const float lcd_gamma
  4929. // 3.) OVERRIDE_FINAL_GAMMA: The user must first define:
  4930. // static const float input_gamma
  4931. // static const float intermediate_gamma
  4932. // static const float output_gamma
  4933. // (intermediate_gamma is for GAMMA_ENCODE_EVERY_FBO.)
  4934. // 4.) OVERRIDE_ALPHA_ASSUMPTIONS: The user must first define:
  4935. // static const bool assume_opaque_alpha
  4936. // The gamma constant overrides must be used in every pass or none,
  4937. // and OVERRIDE_FINAL_GAMMA bypasses all of the SIMULATE* macros.
  4938. // OVERRIDE_ALPHA_ASSUMPTIONS may be set on a per-pass basis.
  4939. // Usage: After setting macros appropriately, ignore gamma correction and
  4940. // replace all tex*D*() calls with equivalent gamma-aware
  4941. // tex*D*_linearize calls, except:
  4942. // 1.) When you read an LUT, use regular tex*D or a gamma-specified
  4943. // function, depending on its gamma encoding:
  4944. // tex*D*_linearize_gamma (takes a runtime gamma parameter)
  4945. // 2.) If you must read pass0's original input in a later pass, use
  4946. // tex2D_linearize_ntsc_gamma. If you want to read pass0's
  4947. // input with gamma-corrected bilinear filtering, consider
  4948. // creating a first linearizing pass and reading from the input
  4949. // of pass1 later.
  4950. // Then, return encode_output(color) from every fragment shader.
  4951. // Finally, use the global gamma_aware_bilinear boolean if you want
  4952. // to statically branch based on whether bilinear filtering is
  4953. // gamma-correct or not (e.g. for placing Gaussian blur samples).
  4954. //
  4955. // Detailed Policy:
  4956. // tex*D*_linearize() functions enforce a consistent gamma-management policy
  4957. // based on the FIRST_PASS and GAMMA_ENCODE_EVERY_FBO settings. They assume
  4958. // their input texture has the same encoding characteristics as the input for
  4959. // the current pass (which doesn't apply to the exceptions listed above).
  4960. // Similarly, encode_output() enforces a policy based on the LAST_PASS and
  4961. // GAMMA_ENCODE_EVERY_FBO settings. Together, they result in one of the
  4962. // following two pipelines.
  4963. // Typical pipeline with intermediate sRGB framebuffers:
  4964. // linear_color = pow(pass0_encoded_color, input_gamma);
  4965. // intermediate_output = linear_color; // Automatic sRGB encoding
  4966. // linear_color = intermediate_output; // Automatic sRGB decoding
  4967. // final_output = pow(intermediate_output, 1.0/output_gamma);
  4968. // Typical pipeline without intermediate sRGB framebuffers:
  4969. // linear_color = pow(pass0_encoded_color, input_gamma);
  4970. // intermediate_output = pow(linear_color, 1.0/intermediate_gamma);
  4971. // linear_color = pow(intermediate_output, intermediate_gamma);
  4972. // final_output = pow(intermediate_output, 1.0/output_gamma);
  4973. // Using GAMMA_ENCODE_EVERY_FBO is much slower, but it's provided as a way to
  4974. // easily get gamma-correctness without banding on devices where sRGB isn't
  4975. // supported.
  4976. //
  4977. // Use This Header to Maximize Code Reuse:
  4978. // The purpose of this header is to provide a consistent interface for texture
  4979. // reads and output gamma-encoding that localizes and abstracts away all the
  4980. // annoying details. This greatly reduces the amount of code in each shader
  4981. // pass that depends on the pass number in the .cgp preset or whether sRGB
  4982. // FBO's are being used: You can trivially change the gamma behavior of your
  4983. // whole pass by commenting or uncommenting 1-3 #defines. To reuse the same
  4984. // code in your first, Nth, and last passes, you can even put it all in another
  4985. // header file and #include it from skeleton .cg files that #define the
  4986. // appropriate pass-specific settings.
  4987. //
  4988. // Rationale for Using Three Macros:
  4989. // This file uses GAMMA_ENCODE_EVERY_FBO instead of an opposite macro like
  4990. // SRGB_PIPELINE to ensure sRGB is assumed by default, which hopefully imposes
  4991. // a lower maintenance burden on each pass. At first glance it seems we could
  4992. // accomplish everything with two macros: GAMMA_CORRECT_IN / GAMMA_CORRECT_OUT.
  4993. // This works for simple use cases where input_gamma == output_gamma, but it
  4994. // breaks down for more complex scenarios like CRT simulation, where the pass
  4995. // number determines the gamma encoding of the input and output.
  4996. /////////////////////////////// BASE CONSTANTS ///////////////////////////////
  4997. // Set standard gamma constants, but allow users to override them:
  4998. #ifndef OVERRIDE_STANDARD_GAMMA
  4999. // Standard encoding gammas:
  5000. static const float ntsc_gamma = 2.2; // Best to use NTSC for PAL too?
  5001. static const float pal_gamma = 2.8; // Never actually 2.8 in practice
  5002. // Typical device decoding gammas (only use for emulating devices):
  5003. // CRT/LCD reference gammas are higher than NTSC and Rec.709 video standard
  5004. // gammas: The standards purposely undercorrected for an analog CRT's
  5005. // assumed 2.5 reference display gamma to maintain contrast in assumed
  5006. // [dark] viewing conditions: http://www.poynton.com/PDFs/GammaFAQ.pdf
  5007. // These unstated assumptions about display gamma and perceptual rendering
  5008. // intent caused a lot of confusion, and more modern CRT's seemed to target
  5009. // NTSC 2.2 gamma with circuitry. LCD displays seem to have followed suit
  5010. // (they struggle near black with 2.5 gamma anyway), especially PC/laptop
  5011. // displays designed to view sRGB in bright environments. (Standards are
  5012. // also in flux again with BT.1886, but it's underspecified for displays.)
  5013. static const float crt_reference_gamma_high = 2.5; // In (2.35, 2.55)
  5014. static const float crt_reference_gamma_low = 2.35; // In (2.35, 2.55)
  5015. static const float lcd_reference_gamma = 2.5; // To match CRT
  5016. static const float crt_office_gamma = 2.2; // Circuitry-adjusted for NTSC
  5017. static const float lcd_office_gamma = 2.2; // Approximates sRGB
  5018. #endif // OVERRIDE_STANDARD_GAMMA
  5019. // Assuming alpha == 1.0 might make it easier for users to avoid some bugs,
  5020. // but only if they're aware of it.
  5021. #ifndef OVERRIDE_ALPHA_ASSUMPTIONS
  5022. static const bool assume_opaque_alpha = false;
  5023. #endif
  5024. /////////////////////// DERIVED CONSTANTS AS FUNCTIONS ///////////////////////
  5025. // gamma-management.h should be compatible with overriding gamma values with
  5026. // runtime user parameters, but we can only define other global constants in
  5027. // terms of static constants, not uniform user parameters. To get around this
  5028. // limitation, we need to define derived constants using functions.
  5029. // Set device gamma constants, but allow users to override them:
  5030. #ifdef OVERRIDE_DEVICE_GAMMA
  5031. // The user promises to globally define the appropriate constants:
  5032. inline float get_crt_gamma() { return crt_gamma; }
  5033. inline float get_gba_gamma() { return gba_gamma; }
  5034. inline float get_lcd_gamma() { return lcd_gamma; }
  5035. #else
  5036. inline float get_crt_gamma() { return crt_reference_gamma_high; }
  5037. inline float get_gba_gamma() { return 3.5; } // Game Boy Advance; in (3.0, 4.0)
  5038. inline float get_lcd_gamma() { return lcd_office_gamma; }
  5039. #endif // OVERRIDE_DEVICE_GAMMA
  5040. // Set decoding/encoding gammas for the first/lass passes, but allow overrides:
  5041. #ifdef OVERRIDE_FINAL_GAMMA
  5042. // The user promises to globally define the appropriate constants:
  5043. inline float get_intermediate_gamma() { return intermediate_gamma; }
  5044. inline float get_input_gamma() { return input_gamma; }
  5045. inline float get_output_gamma() { return output_gamma; }
  5046. #else
  5047. // If we gamma-correct every pass, always use ntsc_gamma between passes to
  5048. // ensure middle passes don't need to care if anything is being simulated:
  5049. inline float get_intermediate_gamma() { return ntsc_gamma; }
  5050. #ifdef SIMULATE_CRT_ON_LCD
  5051. inline float get_input_gamma() { return get_crt_gamma(); }
  5052. inline float get_output_gamma() { return get_lcd_gamma(); }
  5053. #else
  5054. #ifdef SIMULATE_GBA_ON_LCD
  5055. inline float get_input_gamma() { return get_gba_gamma(); }
  5056. inline float get_output_gamma() { return get_lcd_gamma(); }
  5057. #else
  5058. #ifdef SIMULATE_LCD_ON_CRT
  5059. inline float get_input_gamma() { return get_lcd_gamma(); }
  5060. inline float get_output_gamma() { return get_crt_gamma(); }
  5061. #else
  5062. #ifdef SIMULATE_GBA_ON_CRT
  5063. inline float get_input_gamma() { return get_gba_gamma(); }
  5064. inline float get_output_gamma() { return get_crt_gamma(); }
  5065. #else // Don't simulate anything:
  5066. inline float get_input_gamma() { return ntsc_gamma; }
  5067. inline float get_output_gamma() { return ntsc_gamma; }
  5068. #endif // SIMULATE_GBA_ON_CRT
  5069. #endif // SIMULATE_LCD_ON_CRT
  5070. #endif // SIMULATE_GBA_ON_LCD
  5071. #endif // SIMULATE_CRT_ON_LCD
  5072. #endif // OVERRIDE_FINAL_GAMMA
  5073. // Set decoding/encoding gammas for the current pass. Use static constants for
  5074. // linearize_input and gamma_encode_output, because they aren't derived, and
  5075. // they let the compiler do dead-code elimination.
  5076. #ifndef GAMMA_ENCODE_EVERY_FBO
  5077. #ifdef FIRST_PASS
  5078. static const bool linearize_input = true;
  5079. inline float get_pass_input_gamma() { return get_input_gamma(); }
  5080. #else
  5081. static const bool linearize_input = false;
  5082. inline float get_pass_input_gamma() { return 1.0; }
  5083. #endif
  5084. #ifdef LAST_PASS
  5085. static const bool gamma_encode_output = true;
  5086. inline float get_pass_output_gamma() { return get_output_gamma(); }
  5087. #else
  5088. static const bool gamma_encode_output = false;
  5089. inline float get_pass_output_gamma() { return 1.0; }
  5090. #endif
  5091. #else
  5092. static const bool linearize_input = true;
  5093. static const bool gamma_encode_output = true;
  5094. #ifdef FIRST_PASS
  5095. inline float get_pass_input_gamma() { return get_input_gamma(); }
  5096. #else
  5097. inline float get_pass_input_gamma() { return get_intermediate_gamma(); }
  5098. #endif
  5099. #ifdef LAST_PASS
  5100. inline float get_pass_output_gamma() { return get_output_gamma(); }
  5101. #else
  5102. inline float get_pass_output_gamma() { return get_intermediate_gamma(); }
  5103. #endif
  5104. #endif
  5105. // Users might want to know if bilinear filtering will be gamma-correct:
  5106. static const bool gamma_aware_bilinear = !linearize_input;
  5107. ////////////////////// COLOR ENCODING/DECODING FUNCTIONS /////////////////////
  5108. inline float4 encode_output(const float4 color)
  5109. {
  5110. if(gamma_encode_output)
  5111. {
  5112. if(assume_opaque_alpha)
  5113. {
  5114. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), 1.0);
  5115. }
  5116. else
  5117. {
  5118. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), color.a);
  5119. }
  5120. }
  5121. else
  5122. {
  5123. return color;
  5124. }
  5125. }
  5126. inline float4 decode_input(const float4 color)
  5127. {
  5128. if(linearize_input)
  5129. {
  5130. if(assume_opaque_alpha)
  5131. {
  5132. return float4(pow(color.rgb, float3(get_pass_input_gamma())), 1.0);
  5133. }
  5134. else
  5135. {
  5136. return float4(pow(color.rgb, float3(get_pass_input_gamma())), color.a);
  5137. }
  5138. }
  5139. else
  5140. {
  5141. return color;
  5142. }
  5143. }
  5144. inline float4 decode_gamma_input(const float4 color, const float3 gamma)
  5145. {
  5146. if(assume_opaque_alpha)
  5147. {
  5148. return float4(pow(color.rgb, gamma), 1.0);
  5149. }
  5150. else
  5151. {
  5152. return float4(pow(color.rgb, gamma), color.a);
  5153. }
  5154. }
  5155. //TODO/FIXME: I have no idea why replacing the lookup wrappers with this macro fixes the blurs being offset ¯\_(ツ)_/¯
  5156. //#define tex2D_linearize(C, D) decode_input(vec4(texture(C, D)))
  5157. // EDIT: it's the 'const' in front of the coords that's doing it
  5158. /////////////////////////// TEXTURE LOOKUP WRAPPERS //////////////////////////
  5159. // "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  5160. // Provide a wide array of linearizing texture lookup wrapper functions. The
  5161. // Cg shader spec Retroarch uses only allows for 2D textures, but 1D and 3D
  5162. // lookups are provided for completeness in case that changes someday. Nobody
  5163. // is likely to use the *fetch and *proj functions, but they're included just
  5164. // in case. The only tex*D texture sampling functions omitted are:
  5165. // - tex*Dcmpbias
  5166. // - tex*Dcmplod
  5167. // - tex*DARRAY*
  5168. // - tex*DMS*
  5169. // - Variants returning integers
  5170. // Standard line length restrictions are ignored below for vertical brevity.
  5171. /*
  5172. // tex1D:
  5173. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords)
  5174. { return decode_input(tex1D(tex, tex_coords)); }
  5175. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords)
  5176. { return decode_input(tex1D(tex, tex_coords)); }
  5177. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const int texel_off)
  5178. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  5179. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  5180. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  5181. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy)
  5182. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  5183. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy)
  5184. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  5185. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy, const int texel_off)
  5186. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  5187. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy, const int texel_off)
  5188. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  5189. // tex1Dbias:
  5190. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords)
  5191. { return decode_input(tex1Dbias(tex, tex_coords)); }
  5192. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  5193. { return decode_input(tex1Dbias(tex, tex_coords, texel_off)); }
  5194. // tex1Dfetch:
  5195. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords)
  5196. { return decode_input(tex1Dfetch(tex, tex_coords)); }
  5197. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords, const int texel_off)
  5198. { return decode_input(tex1Dfetch(tex, tex_coords, texel_off)); }
  5199. // tex1Dlod:
  5200. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords)
  5201. { return decode_input(tex1Dlod(tex, tex_coords)); }
  5202. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  5203. { return decode_input(tex1Dlod(tex, tex_coords, texel_off)); }
  5204. // tex1Dproj:
  5205. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords)
  5206. { return decode_input(tex1Dproj(tex, tex_coords)); }
  5207. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords)
  5208. { return decode_input(tex1Dproj(tex, tex_coords)); }
  5209. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  5210. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  5211. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords, const int texel_off)
  5212. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  5213. */
  5214. // tex2D:
  5215. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords)
  5216. { return decode_input(COMPAT_TEXTURE(tex, tex_coords)); }
  5217. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords)
  5218. { return decode_input(COMPAT_TEXTURE(tex, tex_coords.xy)); }
  5219. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords, int texel_off)
  5220. { return decode_input(textureLod(tex, tex_coords, texel_off)); }
  5221. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords, int texel_off)
  5222. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  5223. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy)
  5224. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  5225. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy)
  5226. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  5227. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  5228. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  5229. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  5230. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  5231. // tex2Dbias:
  5232. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords)
  5233. //{ return decode_input(tex2Dbias(tex, tex_coords)); }
  5234. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  5235. //{ return decode_input(tex2Dbias(tex, tex_coords, texel_off)); }
  5236. // tex2Dfetch:
  5237. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords)
  5238. //{ return decode_input(tex2Dfetch(tex, tex_coords)); }
  5239. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords, const int texel_off)
  5240. //{ return decode_input(tex2Dfetch(tex, tex_coords, texel_off)); }
  5241. // tex2Dlod:
  5242. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords)
  5243. { return decode_input(textureLod(tex, tex_coords.xy, 0.0)); }
  5244. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords, int texel_off)
  5245. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  5246. /*
  5247. // tex2Dproj:
  5248. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords)
  5249. { return decode_input(tex2Dproj(tex, tex_coords)); }
  5250. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords)
  5251. { return decode_input(tex2Dproj(tex, tex_coords)); }
  5252. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords, const int texel_off)
  5253. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  5254. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  5255. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  5256. */
  5257. /*
  5258. // tex3D:
  5259. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords)
  5260. { return decode_input(tex3D(tex, tex_coords)); }
  5261. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const int texel_off)
  5262. { return decode_input(tex3D(tex, tex_coords, texel_off)); }
  5263. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy)
  5264. { return decode_input(tex3D(tex, tex_coords, dx, dy)); }
  5265. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy, const int texel_off)
  5266. { return decode_input(tex3D(tex, tex_coords, dx, dy, texel_off)); }
  5267. // tex3Dbias:
  5268. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords)
  5269. { return decode_input(tex3Dbias(tex, tex_coords)); }
  5270. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  5271. { return decode_input(tex3Dbias(tex, tex_coords, texel_off)); }
  5272. // tex3Dfetch:
  5273. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords)
  5274. { return decode_input(tex3Dfetch(tex, tex_coords)); }
  5275. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords, const int texel_off)
  5276. { return decode_input(tex3Dfetch(tex, tex_coords, texel_off)); }
  5277. // tex3Dlod:
  5278. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords)
  5279. { return decode_input(tex3Dlod(tex, tex_coords)); }
  5280. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  5281. { return decode_input(tex3Dlod(tex, tex_coords, texel_off)); }
  5282. // tex3Dproj:
  5283. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords)
  5284. { return decode_input(tex3Dproj(tex, tex_coords)); }
  5285. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  5286. { return decode_input(tex3Dproj(tex, tex_coords, texel_off)); }
  5287. /////////*
  5288. // NONSTANDARD "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  5289. // This narrow selection of nonstandard tex2D* functions can be useful:
  5290. // tex2Dlod0: Automatically fill in the tex2D LOD parameter for mip level 0.
  5291. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords)
  5292. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0))); }
  5293. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords, const int texel_off)
  5294. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0), texel_off)); }
  5295. // MANUALLY LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  5296. // Provide a narrower selection of tex2D* wrapper functions that decode an
  5297. // input sample with a specified gamma value. These are useful for reading
  5298. // LUT's and for reading the input of pass0 in a later pass.
  5299. // tex2D:
  5300. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float3 gamma)
  5301. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords), gamma); }
  5302. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float3 gamma)
  5303. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords.xy), gamma); }
  5304. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const int texel_off, const float3 gamma)
  5305. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  5306. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const int texel_off, const float3 gamma)
  5307. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  5308. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  5309. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  5310. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  5311. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  5312. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  5313. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  5314. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  5315. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  5316. /*
  5317. // tex2Dbias:
  5318. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const float3 gamma)
  5319. { return decode_gamma_input(tex2Dbias(tex, tex_coords), gamma); }
  5320. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const int texel_off, const float3 gamma)
  5321. { return decode_gamma_input(tex2Dbias(tex, tex_coords, texel_off), gamma); }
  5322. // tex2Dfetch:
  5323. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const float3 gamma)
  5324. { return decode_gamma_input(tex2Dfetch(tex, tex_coords), gamma); }
  5325. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const int texel_off, const float3 gamma)
  5326. { return decode_gamma_input(tex2Dfetch(tex, tex_coords, texel_off), gamma); }
  5327. */
  5328. // tex2Dlod:
  5329. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, float3 gamma)
  5330. { return decode_gamma_input(textureLod(tex, tex_coords.xy, 0.0), gamma); }
  5331. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, int texel_off, float3 gamma)
  5332. { return decode_gamma_input(textureLod(tex, tex_coords.xy, texel_off), gamma); }
  5333. #endif // GAMMA_MANAGEMENT_H
  5334. //////////////////////////// END GAMMA-MANAGEMENT //////////////////////////
  5335. //////////////////////////////// END INCLUDES ////////////////////////////////
  5336. ///////////////////////////// SCANLINE FUNCTIONS /////////////////////////////
  5337. inline float3 get_gaussian_sigma(const float3 color, const float sigma_range)
  5338. {
  5339. // Requires: Globals:
  5340. // 1.) beam_min_sigma and beam_max_sigma are global floats
  5341. // containing the desired minimum and maximum beam standard
  5342. // deviations, for dim and bright colors respectively.
  5343. // 2.) beam_max_sigma must be > 0.0
  5344. // 3.) beam_min_sigma must be in (0.0, beam_max_sigma]
  5345. // 4.) beam_spot_power must be defined as a global float.
  5346. // Parameters:
  5347. // 1.) color is the underlying source color along a scanline
  5348. // 2.) sigma_range = beam_max_sigma - beam_min_sigma; we take
  5349. // sigma_range as a parameter to avoid repeated computation
  5350. // when beam_{min, max}_sigma are runtime shader parameters
  5351. // Optional: Users may set beam_spot_shape_function to 1 to define the
  5352. // inner f(color) subfunction (see below) as:
  5353. // f(color) = sqrt(1.0 - (color - 1.0)*(color - 1.0))
  5354. // Otherwise (technically, if beam_spot_shape_function < 0.5):
  5355. // f(color) = pow(color, beam_spot_power)
  5356. // Returns: The standard deviation of the Gaussian beam for "color:"
  5357. // sigma = beam_min_sigma + sigma_range * f(color)
  5358. // Details/Discussion:
  5359. // The beam's spot shape vaguely resembles an aspect-corrected f() in the
  5360. // range [0, 1] (not quite, but it's related). f(color) = color makes
  5361. // spots look like diamonds, and a spherical function or cube balances
  5362. // between variable width and a soft/realistic shape. A beam_spot_power
  5363. // > 1.0 can produce an ugly spot shape and more initial clipping, but the
  5364. // final shape also differs based on the horizontal resampling filter and
  5365. // the phosphor bloom. For instance, resampling horizontally in nonlinear
  5366. // light and/or with a sharp (e.g. Lanczos) filter will sharpen the spot
  5367. // shape, but a sixth root is still quite soft. A power function (default
  5368. // 1.0/3.0 beam_spot_power) is most flexible, but a fixed spherical curve
  5369. // has the highest variability without an awful spot shape.
  5370. //
  5371. // beam_min_sigma affects scanline sharpness/aliasing in dim areas, and its
  5372. // difference from beam_max_sigma affects beam width variability. It only
  5373. // affects clipping [for pure Gaussians] if beam_spot_power > 1.0 (which is
  5374. // a conservative estimate for a more complex constraint).
  5375. //
  5376. // beam_max_sigma affects clipping and increasing scanline width/softness
  5377. // as color increases. The wider this is, the more scanlines need to be
  5378. // evaluated to avoid distortion. For a pure Gaussian, the max_beam_sigma
  5379. // at which the first unused scanline always has a weight < 1.0/255.0 is:
  5380. // num scanlines = 2, max_beam_sigma = 0.2089; distortions begin ~0.34
  5381. // num scanlines = 3, max_beam_sigma = 0.3879; distortions begin ~0.52
  5382. // num scanlines = 4, max_beam_sigma = 0.5723; distortions begin ~0.70
  5383. // num scanlines = 5, max_beam_sigma = 0.7591; distortions begin ~0.89
  5384. // num scanlines = 6, max_beam_sigma = 0.9483; distortions begin ~1.08
  5385. // Generalized Gaussians permit more leeway here as steepness increases.
  5386. if(beam_spot_shape_function < 0.5)
  5387. {
  5388. // Use a power function:
  5389. return float3(beam_min_sigma) + sigma_range *
  5390. pow(color, float3(beam_spot_power));
  5391. }
  5392. else
  5393. {
  5394. // Use a spherical function:
  5395. const float3 color_minus_1 = color - float3(1.0);
  5396. return float3(beam_min_sigma) + sigma_range *
  5397. sqrt(float3(1.0) - color_minus_1*color_minus_1);
  5398. }
  5399. }
  5400. inline float3 get_generalized_gaussian_beta(const float3 color,
  5401. const float shape_range)
  5402. {
  5403. // Requires: Globals:
  5404. // 1.) beam_min_shape and beam_max_shape are global floats
  5405. // containing the desired min/max generalized Gaussian
  5406. // beta parameters, for dim and bright colors respectively.
  5407. // 2.) beam_max_shape must be >= 2.0
  5408. // 3.) beam_min_shape must be in [2.0, beam_max_shape]
  5409. // 4.) beam_shape_power must be defined as a global float.
  5410. // Parameters:
  5411. // 1.) color is the underlying source color along a scanline
  5412. // 2.) shape_range = beam_max_shape - beam_min_shape; we take
  5413. // shape_range as a parameter to avoid repeated computation
  5414. // when beam_{min, max}_shape are runtime shader parameters
  5415. // Returns: The type-I generalized Gaussian "shape" parameter beta for
  5416. // the given color.
  5417. // Details/Discussion:
  5418. // Beta affects the scanline distribution as follows:
  5419. // a.) beta < 2.0 narrows the peak to a spike with a discontinuous slope
  5420. // b.) beta == 2.0 just degenerates to a Gaussian
  5421. // c.) beta > 2.0 flattens and widens the peak, then drops off more steeply
  5422. // than a Gaussian. Whereas high sigmas widen and soften peaks, high
  5423. // beta widen and sharpen peaks at the risk of aliasing.
  5424. // Unlike high beam_spot_powers, high beam_shape_powers actually soften shape
  5425. // transitions, whereas lower ones sharpen them (at the risk of aliasing).
  5426. return beam_min_shape + shape_range * pow(color, float3(beam_shape_power));
  5427. }
  5428. float3 scanline_gaussian_integral_contrib(const float3 dist,
  5429. const float3 color, const float pixel_height, const float sigma_range)
  5430. {
  5431. // Requires: 1.) dist is the distance of the [potentially separate R/G/B]
  5432. // point(s) from a scanline in units of scanlines, where
  5433. // 1.0 means the sample point straddles the next scanline.
  5434. // 2.) color is the underlying source color along a scanline.
  5435. // 3.) pixel_height is the output pixel height in scanlines.
  5436. // 4.) Requirements of get_gaussian_sigma() must be met.
  5437. // Returns: Return a scanline's light output over a given pixel.
  5438. // Details:
  5439. // The CRT beam profile follows a roughly Gaussian distribution which is
  5440. // wider for bright colors than dark ones. The integral over the full
  5441. // range of a Gaussian function is always 1.0, so we can vary the beam
  5442. // with a standard deviation without affecting brightness. 'x' = distance:
  5443. // gaussian sample = 1/(sigma*sqrt(2*pi)) * e**(-(x**2)/(2*sigma**2))
  5444. // gaussian integral = 0.5 (1.0 + erf(x/(sigma * sqrt(2))))
  5445. // Use a numerical approximation of the "error function" (the Gaussian
  5446. // indefinite integral) to find the definite integral of the scanline's
  5447. // average brightness over a given pixel area. Even if curved coords were
  5448. // used in this pass, a flat scalar pixel height works almost as well as a
  5449. // pixel height computed from a full pixel-space to scanline-space matrix.
  5450. const float3 sigma = get_gaussian_sigma(color, sigma_range);
  5451. const float3 ph_offset = float3(pixel_height * 0.5);
  5452. const float3 denom_inv = 1.0/(sigma*sqrt(2.0));
  5453. const float3 integral_high = erf((dist + ph_offset)*denom_inv);
  5454. const float3 integral_low = erf((dist - ph_offset)*denom_inv);
  5455. return color * 0.5*(integral_high - integral_low)/pixel_height;
  5456. }
  5457. float3 scanline_generalized_gaussian_integral_contrib(float3 dist,
  5458. float3 color, float pixel_height, float sigma_range,
  5459. float shape_range)
  5460. {
  5461. // Requires: 1.) Requirements of scanline_gaussian_integral_contrib()
  5462. // must be met.
  5463. // 2.) Requirements of get_gaussian_sigma() must be met.
  5464. // 3.) Requirements of get_generalized_gaussian_beta() must be
  5465. // met.
  5466. // Returns: Return a scanline's light output over a given pixel.
  5467. // A generalized Gaussian distribution allows the shape (beta) to vary
  5468. // as well as the width (alpha). "gamma" refers to the gamma function:
  5469. // generalized sample =
  5470. // beta/(2*alpha*gamma(1/beta)) * e**(-(|x|/alpha)**beta)
  5471. // ligamma(s, z) is the lower incomplete gamma function, for which we only
  5472. // implement two of four branches (because we keep 1/beta <= 0.5):
  5473. // generalized integral = 0.5 + 0.5* sign(x) *
  5474. // ligamma(1/beta, (|x|/alpha)**beta)/gamma(1/beta)
  5475. // See get_generalized_gaussian_beta() for a discussion of beta.
  5476. // We base alpha on the intended Gaussian sigma, but it only strictly
  5477. // models models standard deviation at beta == 2, because the standard
  5478. // deviation depends on both alpha and beta (keeping alpha independent is
  5479. // faster and preserves intuitive behavior and a full spectrum of results).
  5480. const float3 alpha = sqrt(2.0) * get_gaussian_sigma(color, sigma_range);
  5481. const float3 beta = get_generalized_gaussian_beta(color, shape_range);
  5482. const float3 alpha_inv = float3(1.0)/alpha;
  5483. const float3 s = float3(1.0)/beta;
  5484. const float3 ph_offset = float3(pixel_height * 0.5);
  5485. // Pass beta to gamma_impl to avoid repeated divides. Similarly pass
  5486. // beta (i.e. 1/s) and 1/gamma(s) to normalized_ligamma_impl.
  5487. const float3 gamma_s_inv = float3(1.0)/gamma_impl(s, beta);
  5488. const float3 dist1 = dist + ph_offset;
  5489. const float3 dist0 = dist - ph_offset;
  5490. const float3 integral_high = sign(dist1) * normalized_ligamma_impl(
  5491. s, pow(abs(dist1)*alpha_inv, beta), beta, gamma_s_inv);
  5492. const float3 integral_low = sign(dist0) * normalized_ligamma_impl(
  5493. s, pow(abs(dist0)*alpha_inv, beta), beta, gamma_s_inv);
  5494. return color * 0.5*(integral_high - integral_low)/pixel_height;
  5495. }
  5496. float3 scanline_gaussian_sampled_contrib(const float3 dist, const float3 color,
  5497. const float pixel_height, const float sigma_range)
  5498. {
  5499. // See scanline_gaussian integral_contrib() for detailed comments!
  5500. // gaussian sample = 1/(sigma*sqrt(2*pi)) * e**(-(x**2)/(2*sigma**2))
  5501. const float3 sigma = get_gaussian_sigma(color, sigma_range);
  5502. // Avoid repeated divides:
  5503. const float3 sigma_inv = float3(1.0)/sigma;
  5504. const float3 inner_denom_inv = 0.5 * sigma_inv * sigma_inv;
  5505. const float3 outer_denom_inv = sigma_inv/sqrt(2.0*pi);
  5506. if(beam_antialias_level > 0.5)
  5507. {
  5508. // Sample 1/3 pixel away in each direction as well:
  5509. const float3 sample_offset = float3(pixel_height/3.0);
  5510. const float3 dist2 = dist + sample_offset;
  5511. const float3 dist3 = abs(dist - sample_offset);
  5512. // Average three pure Gaussian samples:
  5513. const float3 scale = color/3.0 * outer_denom_inv;
  5514. const float3 weight1 = exp(-(dist*dist)*inner_denom_inv);
  5515. const float3 weight2 = exp(-(dist2*dist2)*inner_denom_inv);
  5516. const float3 weight3 = exp(-(dist3*dist3)*inner_denom_inv);
  5517. return scale * (weight1 + weight2 + weight3);
  5518. }
  5519. else
  5520. {
  5521. return color*exp(-(dist*dist)*inner_denom_inv)*outer_denom_inv;
  5522. }
  5523. }
  5524. float3 scanline_generalized_gaussian_sampled_contrib(float3 dist,
  5525. float3 color, float pixel_height, float sigma_range,
  5526. float shape_range)
  5527. {
  5528. // See scanline_generalized_gaussian_integral_contrib() for details!
  5529. // generalized sample =
  5530. // beta/(2*alpha*gamma(1/beta)) * e**(-(|x|/alpha)**beta)
  5531. const float3 alpha = sqrt(2.0) * get_gaussian_sigma(color, sigma_range);
  5532. const float3 beta = get_generalized_gaussian_beta(color, shape_range);
  5533. // Avoid repeated divides:
  5534. const float3 alpha_inv = float3(1.0)/alpha;
  5535. const float3 beta_inv = float3(1.0)/beta;
  5536. const float3 scale = color * beta * 0.5 * alpha_inv /
  5537. gamma_impl(beta_inv, beta);
  5538. if(beam_antialias_level > 0.5)
  5539. {
  5540. // Sample 1/3 pixel closer to and farther from the scanline too.
  5541. const float3 sample_offset = float3(pixel_height/3.0);
  5542. const float3 dist2 = dist + sample_offset;
  5543. const float3 dist3 = abs(dist - sample_offset);
  5544. // Average three generalized Gaussian samples:
  5545. const float3 weight1 = exp(-pow(abs(dist*alpha_inv), beta));
  5546. const float3 weight2 = exp(-pow(abs(dist2*alpha_inv), beta));
  5547. const float3 weight3 = exp(-pow(abs(dist3*alpha_inv), beta));
  5548. return scale/3.0 * (weight1 + weight2 + weight3);
  5549. }
  5550. else
  5551. {
  5552. return scale * exp(-pow(abs(dist*alpha_inv), beta));
  5553. }
  5554. }
  5555. inline float3 scanline_contrib(float3 dist, float3 color,
  5556. float pixel_height, const float sigma_range, const float shape_range)
  5557. {
  5558. // Requires: 1.) Requirements of scanline_gaussian_integral_contrib()
  5559. // must be met.
  5560. // 2.) Requirements of get_gaussian_sigma() must be met.
  5561. // 3.) Requirements of get_generalized_gaussian_beta() must be
  5562. // met.
  5563. // Returns: Return a scanline's light output over a given pixel, using
  5564. // a generalized or pure Gaussian distribution and sampling or
  5565. // integrals as desired by user codepath choices.
  5566. if(beam_generalized_gaussian)
  5567. {
  5568. if(beam_antialias_level > 1.5)
  5569. {
  5570. return scanline_generalized_gaussian_integral_contrib(
  5571. dist, color, pixel_height, sigma_range, shape_range);
  5572. }
  5573. else
  5574. {
  5575. return scanline_generalized_gaussian_sampled_contrib(
  5576. dist, color, pixel_height, sigma_range, shape_range);
  5577. }
  5578. }
  5579. else
  5580. {
  5581. if(beam_antialias_level > 1.5)
  5582. {
  5583. return scanline_gaussian_integral_contrib(
  5584. dist, color, pixel_height, sigma_range);
  5585. }
  5586. else
  5587. {
  5588. return scanline_gaussian_sampled_contrib(
  5589. dist, color, pixel_height, sigma_range);
  5590. }
  5591. }
  5592. }
  5593. inline float3 get_raw_interpolated_color(const float3 color0,
  5594. const float3 color1, const float3 color2, const float3 color3,
  5595. const float4 weights)
  5596. {
  5597. // Use max to avoid bizarre artifacts from negative colors:
  5598. return max(mul(weights, float4x3(color0, color1, color2, color3)), 0.0);
  5599. }
  5600. float3 get_interpolated_linear_color(const float3 color0, const float3 color1,
  5601. const float3 color2, const float3 color3, const float4 weights)
  5602. {
  5603. // Requires: 1.) Requirements of include/gamma-management.h must be met:
  5604. // intermediate_gamma must be globally defined, and input
  5605. // colors are interpreted as linear RGB unless you #define
  5606. // GAMMA_ENCODE_EVERY_FBO (in which case they are
  5607. // interpreted as gamma-encoded with intermediate_gamma).
  5608. // 2.) color0-3 are colors sampled from a texture with tex2D().
  5609. // They are interpreted as defined in requirement 1.
  5610. // 3.) weights contains weights for each color, summing to 1.0.
  5611. // 4.) beam_horiz_linear_rgb_weight must be defined as a global
  5612. // float in [0.0, 1.0] describing how much blending should
  5613. // be done in linear RGB (rest is gamma-corrected RGB).
  5614. // 5.) RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE must be #defined
  5615. // if beam_horiz_linear_rgb_weight is anything other than a
  5616. // static constant, or we may try branching at runtime
  5617. // without dynamic branches allowed (slow).
  5618. // Returns: Return an interpolated color lookup between the four input
  5619. // colors based on the weights in weights. The final color will
  5620. // be a linear RGB value, but the blending will be done as
  5621. // indicated above.
  5622. const float intermediate_gamma = get_intermediate_gamma();
  5623. // Branch if beam_horiz_linear_rgb_weight is static (for free) or if the
  5624. // profile allows dynamic branches (faster than computing extra pows):
  5625. #ifndef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  5626. #define SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  5627. #else
  5628. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  5629. #define SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  5630. #endif
  5631. #endif
  5632. #ifdef SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  5633. // beam_horiz_linear_rgb_weight is static, so we can branch:
  5634. #ifdef GAMMA_ENCODE_EVERY_FBO
  5635. const float3 gamma_mixed_color = pow(get_raw_interpolated_color(
  5636. color0, color1, color2, color3, weights), float3(intermediate_gamma));
  5637. if(beam_horiz_linear_rgb_weight > 0.0)
  5638. {
  5639. const float3 linear_mixed_color = get_raw_interpolated_color(
  5640. pow(color0, float3(intermediate_gamma)),
  5641. pow(color1, float3(intermediate_gamma)),
  5642. pow(color2, float3(intermediate_gamma)),
  5643. pow(color3, float3(intermediate_gamma)),
  5644. weights);
  5645. return lerp(gamma_mixed_color, linear_mixed_color,
  5646. beam_horiz_linear_rgb_weight);
  5647. }
  5648. else
  5649. {
  5650. return gamma_mixed_color;
  5651. }
  5652. #else
  5653. const float3 linear_mixed_color = get_raw_interpolated_color(
  5654. color0, color1, color2, color3, weights);
  5655. if(beam_horiz_linear_rgb_weight < 1.0)
  5656. {
  5657. const float3 gamma_mixed_color = get_raw_interpolated_color(
  5658. pow(color0, float3(1.0/intermediate_gamma)),
  5659. pow(color1, float3(1.0/intermediate_gamma)),
  5660. pow(color2, float3(1.0/intermediate_gamma)),
  5661. pow(color3, float3(1.0/intermediate_gamma)),
  5662. weights);
  5663. return lerp(gamma_mixed_color, linear_mixed_color,
  5664. beam_horiz_linear_rgb_weight);
  5665. }
  5666. else
  5667. {
  5668. return linear_mixed_color;
  5669. }
  5670. #endif // GAMMA_ENCODE_EVERY_FBO
  5671. #else
  5672. #ifdef GAMMA_ENCODE_EVERY_FBO
  5673. // Inputs: color0-3 are colors in gamma-encoded RGB.
  5674. const float3 gamma_mixed_color = pow(get_raw_interpolated_color(
  5675. color0, color1, color2, color3, weights), intermediate_gamma);
  5676. const float3 linear_mixed_color = get_raw_interpolated_color(
  5677. pow(color0, float3(intermediate_gamma)),
  5678. pow(color1, float3(intermediate_gamma)),
  5679. pow(color2, float3(intermediate_gamma)),
  5680. pow(color3, float3(intermediate_gamma)),
  5681. weights);
  5682. return lerp(gamma_mixed_color, linear_mixed_color,
  5683. beam_horiz_linear_rgb_weight);
  5684. #else
  5685. // Inputs: color0-3 are colors in linear RGB.
  5686. const float3 linear_mixed_color = get_raw_interpolated_color(
  5687. color0, color1, color2, color3, weights);
  5688. const float3 gamma_mixed_color = get_raw_interpolated_color(
  5689. pow(color0, float3(1.0/intermediate_gamma)),
  5690. pow(color1, float3(1.0/intermediate_gamma)),
  5691. pow(color2, float3(1.0/intermediate_gamma)),
  5692. pow(color3, float3(1.0/intermediate_gamma)),
  5693. weights);
  5694. // wtf fixme
  5695. // const float beam_horiz_linear_rgb_weight1 = 1.0;
  5696. return lerp(gamma_mixed_color, linear_mixed_color,
  5697. beam_horiz_linear_rgb_weight);
  5698. #endif // GAMMA_ENCODE_EVERY_FBO
  5699. #endif // SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  5700. }
  5701. float3 get_scanline_color(const sampler2D tex, const float2 scanline_uv,
  5702. const float2 uv_step_x, const float4 weights)
  5703. {
  5704. // Requires: 1.) scanline_uv must be vertically snapped to the caller's
  5705. // desired line or scanline and horizontally snapped to the
  5706. // texel just left of the output pixel (color1)
  5707. // 2.) uv_step_x must contain the horizontal uv distance
  5708. // between texels.
  5709. // 3.) weights must contain interpolation filter weights for
  5710. // color0, color1, color2, and color3, where color1 is just
  5711. // left of the output pixel.
  5712. // Returns: Return a horizontally interpolated texture lookup using 2-4
  5713. // nearby texels, according to weights and the conventions of
  5714. // get_interpolated_linear_color().
  5715. // We can ignore the outside texture lookups for Quilez resampling.
  5716. const float3 color1 = COMPAT_TEXTURE(tex, scanline_uv).rgb;
  5717. const float3 color2 = COMPAT_TEXTURE(tex, scanline_uv + uv_step_x).rgb;
  5718. float3 color0 = float3(0.0);
  5719. float3 color3 = float3(0.0);
  5720. if(beam_horiz_filter > 0.5)
  5721. {
  5722. color0 = COMPAT_TEXTURE(tex, scanline_uv - uv_step_x).rgb;
  5723. color3 = COMPAT_TEXTURE(tex, scanline_uv + 2.0 * uv_step_x).rgb;
  5724. }
  5725. // Sample the texture as-is, whether it's linear or gamma-encoded:
  5726. // get_interpolated_linear_color() will handle the difference.
  5727. return get_interpolated_linear_color(color0, color1, color2, color3, weights);
  5728. }
  5729. float3 sample_single_scanline_horizontal(const sampler2D tex,
  5730. const float2 tex_uv, const float2 tex_size,
  5731. const float2 texture_size_inv)
  5732. {
  5733. // TODO: Add function requirements.
  5734. // Snap to the previous texel and get sample dists from 2/4 nearby texels:
  5735. const float2 curr_texel = tex_uv * tex_size;
  5736. // Use under_half to fix a rounding bug right around exact texel locations.
  5737. const float2 prev_texel =
  5738. floor(curr_texel - float2(under_half)) + float2(0.5);
  5739. const float2 prev_texel_hor = float2(prev_texel.x, curr_texel.y);
  5740. const float2 prev_texel_hor_uv = prev_texel_hor * texture_size_inv;
  5741. const float prev_dist = curr_texel.x - prev_texel_hor.x;
  5742. const float4 sample_dists = float4(1.0 + prev_dist, prev_dist,
  5743. 1.0 - prev_dist, 2.0 - prev_dist);
  5744. // Get Quilez, Lanczos2, or Gaussian resize weights for 2/4 nearby texels:
  5745. float4 weights;
  5746. if(beam_horiz_filter < 0.5)
  5747. {
  5748. // Quilez:
  5749. const float x = sample_dists.y;
  5750. const float w2 = x*x*x*(x*(x*6.0 - 15.0) + 10.0);
  5751. weights = float4(0.0, 1.0 - w2, w2, 0.0);
  5752. }
  5753. else if(beam_horiz_filter < 1.5)
  5754. {
  5755. // Gaussian:
  5756. float inner_denom_inv = 1.0/(2.0*beam_horiz_sigma*beam_horiz_sigma);
  5757. weights = exp(-(sample_dists*sample_dists)*inner_denom_inv);
  5758. }
  5759. else
  5760. {
  5761. // Lanczos2:
  5762. const float4 pi_dists = FIX_ZERO(sample_dists * pi);
  5763. weights = 2.0 * sin(pi_dists) * sin(pi_dists * 0.5) /
  5764. (pi_dists * pi_dists);
  5765. }
  5766. // Ensure the weight sum == 1.0:
  5767. const float4 final_weights = weights/dot(weights, float4(1.0));
  5768. // Get the interpolated horizontal scanline color:
  5769. const float2 uv_step_x = float2(texture_size_inv.x, 0.0);
  5770. return get_scanline_color(
  5771. tex, prev_texel_hor_uv, uv_step_x, final_weights);
  5772. }
  5773. float3 sample_rgb_scanline_horizontal(const sampler2D tex,
  5774. const float2 tex_uv, const float2 tex_size,
  5775. const float2 texture_size_inv)
  5776. {
  5777. // TODO: Add function requirements.
  5778. // Rely on a helper to make convergence easier.
  5779. if(beam_misconvergence)
  5780. {
  5781. const float3 convergence_offsets_rgb =
  5782. get_convergence_offsets_x_vector();
  5783. const float3 offset_u_rgb =
  5784. convergence_offsets_rgb * texture_size_inv.xxx;
  5785. const float2 scanline_uv_r = tex_uv - float2(offset_u_rgb.r, 0.0);
  5786. const float2 scanline_uv_g = tex_uv - float2(offset_u_rgb.g, 0.0);
  5787. const float2 scanline_uv_b = tex_uv - float2(offset_u_rgb.b, 0.0);
  5788. const float3 sample_r = sample_single_scanline_horizontal(
  5789. tex, scanline_uv_r, tex_size, texture_size_inv);
  5790. const float3 sample_g = sample_single_scanline_horizontal(
  5791. tex, scanline_uv_g, tex_size, texture_size_inv);
  5792. const float3 sample_b = sample_single_scanline_horizontal(
  5793. tex, scanline_uv_b, tex_size, texture_size_inv);
  5794. return float3(sample_r.r, sample_g.g, sample_b.b);
  5795. }
  5796. else
  5797. {
  5798. return sample_single_scanline_horizontal(tex, tex_uv, tex_size,
  5799. texture_size_inv);
  5800. }
  5801. }
  5802. float2 get_last_scanline_uv(const float2 tex_uv, const float2 tex_size,
  5803. const float2 texture_size_inv, const float2 il_step_multiple,
  5804. const float frame_count, out float dist)
  5805. {
  5806. // Compute texture coords for the last/upper scanline, accounting for
  5807. // interlacing: With interlacing, only consider even/odd scanlines every
  5808. // other frame. Top-field first (TFF) order puts even scanlines on even
  5809. // frames, and BFF order puts them on odd frames. Texels are centered at:
  5810. // frac(tex_uv * tex_size) == x.5
  5811. // Caution: If these coordinates ever seem incorrect, first make sure it's
  5812. // not because anisotropic filtering is blurring across field boundaries.
  5813. // Note: TFF/BFF won't matter for sources that double-weave or similar.
  5814. // wtf fixme
  5815. // const float interlace_bff1 = 1.0;
  5816. const float field_offset = floor(il_step_multiple.y * 0.75) *
  5817. fmod(frame_count + float(interlace_bff), 2.0);
  5818. const float2 curr_texel = tex_uv * tex_size;
  5819. // Use under_half to fix a rounding bug right around exact texel locations.
  5820. const float2 prev_texel_num = floor(curr_texel - float2(under_half));
  5821. const float wrong_field = fmod(
  5822. prev_texel_num.y + field_offset, il_step_multiple.y);
  5823. const float2 scanline_texel_num = prev_texel_num - float2(0.0, wrong_field);
  5824. // Snap to the center of the previous scanline in the current field:
  5825. const float2 scanline_texel = scanline_texel_num + float2(0.5);
  5826. const float2 scanline_uv = scanline_texel * texture_size_inv;
  5827. // Save the sample's distance from the scanline, in units of scanlines:
  5828. dist = (curr_texel.y - scanline_texel.y)/il_step_multiple.y;
  5829. return scanline_uv;
  5830. }
  5831. inline bool is_interlaced(float num_lines)
  5832. {
  5833. // Detect interlacing based on the number of lines in the source.
  5834. if(interlace_detect)
  5835. {
  5836. // NTSC: 525 lines, 262.5/field; 486 active (2 half-lines), 243/field
  5837. // NTSC Emulators: Typically 224 or 240 lines
  5838. // PAL: 625 lines, 312.5/field; 576 active (typical), 288/field
  5839. // PAL Emulators: ?
  5840. // ATSC: 720p, 1080i, 1080p
  5841. // Where do we place our cutoffs? Assumptions:
  5842. // 1.) We only need to care about active lines.
  5843. // 2.) Anything > 288 and <= 576 lines is probably interlaced.
  5844. // 3.) Anything > 576 lines is probably not interlaced...
  5845. // 4.) ...except 1080 lines, which is a crapshoot (user decision).
  5846. // 5.) Just in case the main program uses calculated video sizes,
  5847. // we should nudge the float thresholds a bit.
  5848. const bool sd_interlace = ((num_lines > 288.5) && (num_lines < 576.5));
  5849. const bool hd_interlace = bool(interlace_1080i) ?
  5850. ((num_lines > 1079.5) && (num_lines < 1080.5)) :
  5851. false;
  5852. return (sd_interlace || hd_interlace);
  5853. }
  5854. else
  5855. {
  5856. return false;
  5857. }
  5858. }
  5859. #endif // SCANLINE_FUNCTIONS_H
  5860. ///////////////////////////// END SCANLINE-FUNCTIONS ////////////////////////////
  5861. ////////////////////////////// END VERTEX-INCLUDES //////////////////////////////
  5862. #undef COMPAT_PRECISION
  5863. #undef COMPAT_TEXTURE
  5864. float bloom_approx_scale_x = targetSize.x / sourceSize[0].y;
  5865. const float max_viewport_size_x = 1080.0*1024.0*(4.0/3.0);
  5866. const float bloom_diff_thresh_ = 1.0/256.0;
  5867. // copied from bloom-functions.h
  5868. inline float get_min_sigma_to_blur_triad(const float triad_size,
  5869. const float thresh)
  5870. {
  5871. // Requires: 1.) triad_size is the final phosphor triad size in pixels
  5872. // 2.) thresh is the max desired pixel difference in the
  5873. // blurred triad (e.g. 1.0/256.0).
  5874. // Returns: Return the minimum sigma that will fully blur a phosphor
  5875. // triad on the screen to an even color, within thresh.
  5876. // This closed-form function was found by curve-fitting data.
  5877. // Estimate: max error = ~0.086036, mean sq. error = ~0.0013387:
  5878. return -0.05168 + 0.6113*triad_size -
  5879. 1.122*triad_size*sqrt(0.000416 + thresh);
  5880. // Estimate: max error = ~0.16486, mean sq. error = ~0.0041041:
  5881. //return 0.5985*triad_size - triad_size*sqrt(thresh)
  5882. }
  5883. void main() {
  5884. gl_Position = position;
  5885. vTexCoord = texCoord * 1.0001;
  5886. float2 tex_uv = vTexCoord.xy;
  5887. // These things keep causing weird behavior and they're not needed except for NPOT, so...
  5888. /* // Our various input textures use different coords:
  5889. const float2 video_uv = tex_uv;// * texture_size/video_size;
  5890. video_uv = video_uv;
  5891. scanline_tex_uv = video_uv;// * MASKED_SCANLINESvideo_size /
  5892. MASKED_SCANLINEStexture_size;
  5893. halation_tex_uv = video_uv;// * HALATION_BLURvideo_size /
  5894. HALATION_BLURtexture_size;
  5895. brightpass_tex_uv = video_uv;// * BRIGHTPASSvideo_size /
  5896. BRIGHTPASStexture_size;
  5897. bloom_tex_uv = tex_uv;
  5898. */
  5899. // We're horizontally blurring the bloom input (vertically blurred
  5900. // brightpass). Get the uv distance between output pixels / input texels
  5901. // in the horizontal direction (this pass must NOT resize):
  5902. bloom_dxdy = float2(1.0/texture_size.x, 0.0);
  5903. // Calculate a runtime bloom_sigma in case it's needed:
  5904. const float mask_tile_size_x = get_resized_mask_tile_size(
  5905. output_size, output_size * mask_resize_viewport_scale, false).x;
  5906. bloom_sigma_runtime = get_min_sigma_to_blur_triad(
  5907. mask_tile_size_x / mask_triads_per_tile, bloom_diff_thresh_);
  5908. }