brightpass.vs 339 KB

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