Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop-gpui): match Apple's glass size adaptation, lens falloff, colour and tint

Richie McIlroye40da5c1fc9f
diff --git a/apps/desktop-gpui/glass/presets.json b/apps/desktop-gpui/glass/presets.json
index b5b872eb0..d6b3e17c0 100644
--- a/apps/desktop-gpui/glass/presets.json
+++ b/apps/desktop-gpui/glass/presets.json
@@ -1,138 +1,772 @@
{
"clear-dark": {
- "bend": -2.412919521331787,
- "blur_k": 0.18000054359436035,
+ "bend_base": 0.0,
+ "bend_k": 0.5220050811767578,
+ "bend_max": 44.700069427490234,
+ "blur_k": 0.2080000936985016,
"blur_max": 20.0,
- "glow": -9.978866728488356e-6,
- "glow_width": 39.30601119995117,
+ "glow": -0.023217225447297096,
+ "glow_width": 0.5,
"hairline": [
- 0.5050199031829834, -0.002001264365389943, 1.0410776138305664,
- -0.00509136077016592
+ 0.593367338180542,
+ -0.05059341341257095,
+ 1.0214955806732178,
+ 0.0020442637614905834
],
- "lens_curve": 0.3599303960800171,
- "light_angle": 2.3112025260925293,
- "line": 0.0018150180112570524,
- "line_lit": 0.0017182374140247703,
- "line_width": 0.994491457939148,
+ "lens_curve": 1.0,
+ "light_angle": -0.21393775939941406,
+ "line": 0.022001737728714943,
+ "line_lit": 4.008400719612837e-05,
+ "line_width": 0.977599024772644,
"opacity": 0.6000000238418579,
"poly": [
- 0.6313937902450562, 0.7283032536506653, -0.7202409505844116,
- 0.7613860964775085, -2.0895676612854004, 1.455474615097046,
- 0.11192644387483597, 0.08696344494819641, -0.08549253642559052,
- -0.5280044078826904, 1.2200205326080322, -0.8582108616828918,
- 0.09805495291948318, -0.07880198210477829, 0.8358877301216125,
- -0.0669502466917038, 0.0785026028752327, -0.18421262502670288,
- 0.11133701354265213, 0.045185938477516174, 0.023230290040373802,
- -0.010092880576848984, -0.06803300976753235, 0.10296168178319931,
- -0.0751410573720932, 0.09795161336660385, -0.17431367933750153,
- -0.31713956594467163, 1.1713937520980835, 0.1505192369222641,
- 0.10798941552639008, -0.3602425456047058, 0.06854856759309769,
- 0.10419972240924835, 0.021173598244786263, -0.08950604498386383,
- -0.09568458050489426, 0.12689803540706635, 0.09791429340839386
+ 0.9304253458976746,
+ -0.12481314688920975,
+ -0.10088877379894257,
+ -0.004045877140015364,
+ -0.07585885375738144,
+ 0.14717964828014374,
+ -0.07393107563257217,
+ 0.06024130806326866,
+ -0.03879432752728462,
+ -0.000815805746242404,
+ 0.03807489201426506,
+ -0.07791057974100113,
+ 0.016926679760217667,
+ 0.0058880094438791275,
+ 0.03510991483926773,
+ -0.025886960327625275,
+ 0.016199838370084763,
+ -0.03267030790448189,
+ 0.01904219388961792,
+ 0.09808459132909775,
+ -0.00837408285588026,
+ 0.7795435786247253,
+ -0.07242636382579803,
+ -0.04168546944856644,
+ 0.04919590428471565,
+ 0.11554957926273346,
+ -0.059605952352285385,
+ -0.02326720952987671,
+ -0.007376297377049923,
+ -0.0005821718950755894,
+ -0.04080246761441231,
+ -0.05716409534215927,
+ 0.043717119842767715,
+ 0.023880789056420326,
+ 0.012365260161459446,
+ 0.026850342750549316,
+ -0.011099698953330517,
+ -0.011699579656124115,
+ -0.0034550407435745,
+ 0.0981355756521225,
+ -0.040654897689819336,
+ -0.15084543824195862,
+ 0.8951388597488403,
+ -0.00773319648578763,
+ -0.06471528857946396,
+ 0.08432544767856598,
+ 0.0036153215914964676,
+ 0.015856880694627762,
+ -0.013019285164773464,
+ -0.008954270742833614,
+ 0.056587692350149155,
+ -0.06041482836008072,
+ 0.033091913908720016,
+ 0.0052201892249286175,
+ -0.029888352379202843,
+ -0.02021406590938568,
+ 0.01316642202436924,
+ 0.017514236271381378,
+ -0.01460269745439291,
+ 0.0980868712067604
],
- "rim_k": 0.2883424758911133,
- "rim_max": 24.872886657714844
+ "rim_base": 3.5,
+ "rim_k": 0.039999820291996,
+ "rim_max": 7.899994850158691,
+ "tint": {
+ "high": [
+ [
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068
+ ],
+ [
+ -0.1654,
+ 0.043,
+ 0.043,
+ 0.1021,
+ 0.1161
+ ],
+ [
+ -0.1202,
+ 0.1449,
+ 0.1839,
+ 0.211,
+ 0.2499
+ ],
+ [
+ -0.0202,
+ 0.2129,
+ 0.2659,
+ 0.3087,
+ 0.3616
+ ],
+ [
+ 0.0908,
+ 0.2828,
+ 0.3405,
+ 0.4175,
+ 0.4843
+ ],
+ [
+ 0.1908,
+ 0.3508,
+ 0.4318,
+ 0.5262,
+ 0.6071
+ ],
+ [
+ 0.2908,
+ 0.4314,
+ 0.5405,
+ 0.6505,
+ 0.7616
+ ],
+ [
+ 0.4018,
+ 0.5174,
+ 0.6456,
+ 0.7749,
+ 0.9161
+ ],
+ [
+ 0.4908,
+ 0.5777,
+ 0.7453,
+ 0.9103,
+ 1.0044
+ ],
+ [
+ 0.6675,
+ 0.6379,
+ 0.8026,
+ 0.9573,
+ 1.0044
+ ],
+ [
+ 0.8162,
+ 0.5092,
+ 0.8019,
+ 0.9504,
+ 1.0044
+ ],
+ [
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759
+ ]
+ ],
+ "kind": "layer",
+ "low": [
+ [
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068
+ ],
+ [
+ -0.1654,
+ 0.043,
+ 0.043,
+ -0.0162,
+ -0.0302
+ ],
+ [
+ -0.1202,
+ 0.0719,
+ 0.0329,
+ 0.0092,
+ -0.0297
+ ],
+ [
+ -0.0202,
+ 0.1013,
+ 0.0482,
+ 0.0018,
+ -0.0511
+ ],
+ [
+ 0.0908,
+ 0.1434,
+ 0.0782,
+ 0.0054,
+ -0.0615
+ ],
+ [
+ 0.1908,
+ 0.1728,
+ 0.0917,
+ -0.0131,
+ -0.0939
+ ],
+ [
+ 0.2908,
+ 0.2046,
+ 0.1028,
+ -0.0032,
+ -0.1142
+ ],
+ [
+ 0.4018,
+ 0.2309,
+ 0.1102,
+ -0.0153,
+ -0.1565
+ ],
+ [
+ 0.4908,
+ 0.2536,
+ 0.1011,
+ -0.0822,
+ -0.1764
+ ],
+ [
+ 0.6675,
+ 0.3201,
+ 0.1707,
+ 0.0269,
+ -0.0202
+ ],
+ [
+ 0.8162,
+ 0.5092,
+ 0.2201,
+ 0.0576,
+ 0.014
+ ],
+ [
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759
+ ]
+ ]
+ }
},
"clear-light": {
- "bend": -2.4594221115112305,
- "blur_k": 0.17999997735023499,
+ "bend_base": 0.0,
+ "bend_k": 0.5219979286193848,
+ "bend_max": 44.700042724609375,
+ "blur_k": 0.20799961686134338,
"blur_max": 20.0,
- "glow": -0.0408473014831543,
+ "glow": -0.07008297741413116,
"glow_width": 0.5,
"hairline": [
- 0.6450185179710388, -0.016545917838811874, 1.0230517387390137,
- 0.008764644153416157
+ 0.8242620229721069,
+ -0.1320314109325409,
+ 0.9752746820449829,
+ 0.04035332053899765
],
- "lens_curve": 0.318873792886734,
- "light_angle": 2.6443076133728027,
- "line": 0.01456276886165142,
- "line_lit": 0.0015534033300355077,
- "line_width": 1.097947359085083,
+ "lens_curve": 1.0,
+ "light_angle": -2.847440719604492,
+ "line": 0.041799671947956085,
+ "line_lit": -0.0001845387159846723,
+ "line_width": 0.8613333702087402,
"opacity": 0.6000000238418579,
"poly": [
- 0.2497211992740631, 0.7583296895027161, -0.36811646819114685,
- 1.273596167564392, -1.9042826890945435, 0.8599693775177002,
- -0.0514889694750309, 0.052962444722652435, -0.08220545202493668,
- -0.7352914810180664, 1.1641223430633545, -0.5389814972877502,
- 0.2785186767578125, -0.03988504037261009, 0.7219523787498474,
- -0.007673143874853849, 0.03376581892371178, -0.050814464688301086,
- 0.03104168362915516, 0.0132481399923563, -0.0016589678125455976,
- -0.007338891737163067, -0.033974405378103256, 0.04808909818530083,
- -0.028364654630422592, 0.27844366431236267, -0.0301153976470232,
- 0.1788342148065567, 0.5316532850265503, 0.18545162677764893,
- -0.6017318367958069, 0.36461755633354187, -0.07064586132764816,
- 0.13311389088630676, -0.007584464270621538, -0.13774992525577545,
- 0.3131157159805298, -0.1805034577846527, 0.2784975469112396
+ 1.1434636116027832,
+ -0.27574145793914795,
+ -0.17895224690437317,
+ -0.0836833268404007,
+ 0.1225225031375885,
+ 0.1864597499370575,
+ -0.37334734201431274,
+ 0.4921723008155823,
+ -0.3727247416973114,
+ -0.12790314853191376,
+ -0.02433956041932106,
+ -0.05253470316529274,
+ 0.29910096526145935,
+ 0.11252079159021378,
+ 0.02607177011668682,
+ -0.18502143025398254,
+ 0.15787704288959503,
+ -0.2634184658527374,
+ 0.075639508664608,
+ 0.27857351303100586,
+ -0.03583918884396553,
+ 0.7502926588058472,
+ -0.02740371786057949,
+ -0.01758371666073799,
+ 0.02899535372853279,
+ 0.023246919736266136,
+ -0.019552607089281082,
+ -0.0588289238512516,
+ 0.0193873830139637,
+ -0.005965698044747114,
+ -0.034728698432445526,
+ -0.0037371099460870028,
+ 0.019717223942279816,
+ 0.017275473102927208,
+ 0.005123075097799301,
+ 0.04545024037361145,
+ -0.0219881571829319,
+ 0.006534123793244362,
+ -0.012194417417049408,
+ 0.27857986092567444,
+ -0.07504594326019287,
+ -0.19895681738853455,
+ 0.9592817425727844,
+ -0.06376186013221741,
+ 0.014718386344611645,
+ -0.15277686715126038,
+ 0.07323915511369705,
+ 0.006354332435876131,
+ 0.10439865291118622,
+ 0.04123719036579132,
+ 0.035259801894426346,
+ -0.11292031407356262,
+ 0.010606243275105953,
+ 0.0005314881564117968,
+ -9.800001862458885e-05,
+ -0.18178176879882812,
+ 0.060928262770175934,
+ 0.37380093336105347,
+ -0.21683937311172485,
+ 0.27857956290245056
],
- "rim_k": 0.2952793836593628,
- "rim_max": 26.819894790649414
+ "rim_base": 3.5,
+ "rim_k": 0.04000019654631615,
+ "rim_max": 7.90000057220459,
+ "tint": {
+ "high": [
+ [
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068
+ ],
+ [
+ -0.1654,
+ 0.043,
+ 0.043,
+ 0.1021,
+ 0.1161
+ ],
+ [
+ -0.1202,
+ 0.1449,
+ 0.1839,
+ 0.211,
+ 0.2499
+ ],
+ [
+ -0.0202,
+ 0.2129,
+ 0.2659,
+ 0.3087,
+ 0.3616
+ ],
+ [
+ 0.0908,
+ 0.2828,
+ 0.3405,
+ 0.4175,
+ 0.4843
+ ],
+ [
+ 0.1908,
+ 0.3508,
+ 0.4318,
+ 0.5262,
+ 0.6071
+ ],
+ [
+ 0.2908,
+ 0.4314,
+ 0.5405,
+ 0.6505,
+ 0.7616
+ ],
+ [
+ 0.4018,
+ 0.5174,
+ 0.6456,
+ 0.7749,
+ 0.9161
+ ],
+ [
+ 0.4908,
+ 0.5777,
+ 0.7453,
+ 0.9103,
+ 1.0044
+ ],
+ [
+ 0.6675,
+ 0.6379,
+ 0.8026,
+ 0.9573,
+ 1.0044
+ ],
+ [
+ 0.8162,
+ 0.5092,
+ 0.8019,
+ 0.9504,
+ 1.0044
+ ],
+ [
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759
+ ]
+ ],
+ "kind": "layer",
+ "low": [
+ [
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068,
+ -0.068
+ ],
+ [
+ -0.1654,
+ 0.043,
+ 0.043,
+ -0.0162,
+ -0.0302
+ ],
+ [
+ -0.1202,
+ 0.0719,
+ 0.0329,
+ 0.0092,
+ -0.0297
+ ],
+ [
+ -0.0202,
+ 0.1013,
+ 0.0482,
+ 0.0018,
+ -0.0511
+ ],
+ [
+ 0.0908,
+ 0.1434,
+ 0.0782,
+ 0.0054,
+ -0.0615
+ ],
+ [
+ 0.1908,
+ 0.1728,
+ 0.0917,
+ -0.0131,
+ -0.0939
+ ],
+ [
+ 0.2908,
+ 0.2046,
+ 0.1028,
+ -0.0032,
+ -0.1142
+ ],
+ [
+ 0.4018,
+ 0.2309,
+ 0.1102,
+ -0.0153,
+ -0.1565
+ ],
+ [
+ 0.4908,
+ 0.2536,
+ 0.1011,
+ -0.0822,
+ -0.1764
+ ],
+ [
+ 0.6675,
+ 0.3201,
+ 0.1707,
+ 0.0269,
+ -0.0202
+ ],
+ [
+ 0.8162,
+ 0.5092,
+ 0.2201,
+ 0.0576,
+ 0.014
+ ],
+ [
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759,
+ 0.9759
+ ]
+ ]
+ }
},
"regular-dark": {
- "bend": -1.6669726371765137,
+ "adapt": {
+ "large": 104.5999984741211,
+ "poly": [
+ -2.121854066848755,
+ 4.518572807312012,
+ -1.3435695171356201,
+ 0.776678204536438,
+ -9.252964973449707,
+ 0.28634369373321533,
+ 4.4394073486328125,
+ -1.3082177639007568,
+ 4.613157272338867,
+ 0.1885642260313034,
+ 4.356483459472656,
+ 2.1629786491394043,
+ -1.000849723815918,
+ -1.141960620880127,
+ -1.716369390487671,
+ 4.243387222290039,
+ -2.109083414077759,
+ -3.6303977966308594,
+ -1.3335038423538208,
+ 0.07930468022823334,
+ -0.06321439892053604,
+ 1.6568504571914673,
+ -0.5502462983131409,
+ 0.47407275438308716,
+ -0.5093795657157898,
+ 0.18556971848011017,
+ -1.3741369247436523,
+ 0.4993451237678528,
+ 0.30742496252059937,
+ -0.13183802366256714,
+ -0.43906792998313904,
+ 0.5691431164741516,
+ -0.260586142539978,
+ -0.2801496684551239,
+ 1.1938122510910034,
+ 0.6415687203407288,
+ 0.2897544205188751,
+ -1.767791986465454,
+ 0.18552877008914948,
+ 0.07926828414201736,
+ -0.7065837979316711,
+ -1.389380693435669,
+ 3.1453685760498047,
+ 1.1397459506988525,
+ 1.6847290992736816,
+ -3.872493028640747,
+ -0.043841056525707245,
+ 0.8904445767402649,
+ -0.2337447702884674,
+ 0.0994030013680458,
+ -0.5763757824897766,
+ 1.5949156284332275,
+ -1.1367660760879517,
+ -1.1690083742141724,
+ 0.5194790959358215,
+ -1.9919798374176025,
+ 0.5003051161766052,
+ 0.38825687766075134,
+ 1.7843526601791382,
+ 0.07925731688737869
+ ],
+ "small": 64.0
+ },
+ "bend_base": 10.7000732421875,
+ "bend_k": 0.0820002481341362,
+ "bend_max": 26.200000762939453,
"blur_k": 0.14000000059604645,
"blur_max": 12.0,
- "glow": 0.024336621165275574,
- "glow_width": 51.54517364501953,
+ "glow": -0.0030187764205038548,
+ "glow_width": 0.5,
"hairline": [
- 0.2600359320640564, 0.103030264377594, 0.5471664667129517,
- 0.04482661187648773
+ 0.1722264587879181,
+ 0.17626123130321503,
+ 0.48439785838127136,
+ 0.10737959295511246
],
- "lens_curve": 0.5919271111488342,
- "light_angle": -2.782675266265869,
- "line": 0.011403294280171394,
- "line_lit": 0.011242559179663658,
- "line_width": 0.3977275788784027,
+ "lens_curve": 1.0,
+ "light_angle": 3.786133289337158,
+ "line": -0.061254773288965225,
+ "line_lit": -0.001504245214164257,
+ "line_width": 0.30000001192092896,
"opacity": 0.6000000238418579,
"poly": [
- 1.1208113431930542, 0.769611120223999, -0.9219794273376465,
- 0.1965949982404709, -1.9167686700820923, 1.746425747871399,
- -0.3972877562046051, 0.10475105792284012, -0.1348458230495453,
- -0.213811457157135, 1.0382335186004639, -1.0049047470092773,
- 0.06521148979663849, -0.11392313241958618, 1.4205176830291748,
- -0.28513824939727783, 0.0018862647702917457, -0.9691377878189087,
- 0.4069260358810425, 0.0062097590416669846, -0.0784282386302948,
- 0.034528374671936035, -0.00854511745274067, 0.1753605753183365,
- -0.20346999168395996, 0.06513476371765137, -0.15799254179000854,
- -0.39501243829727173, 1.5855051279067993, -0.05833205580711365,
- 0.4637044072151184, -0.6609259247779846, 0.17491891980171204,
- -0.48810815811157227, -0.048988454043865204, 0.038651589304208755,
- -0.36601346731185913, 0.29942595958709717, 0.06502226740121841
+ 1.1187022924423218,
+ 0.03367934003472328,
+ -0.10441520810127258,
+ -0.13338716328144073,
+ 0.29741689562797546,
+ 0.19946272671222687,
+ -0.5520410537719727,
+ -0.9366043210029602,
+ 0.44745180010795593,
+ 0.0030512954108417034,
+ -0.45639705657958984,
+ -0.0059659117832779884,
+ -0.07397174090147018,
+ 0.006216675043106079,
+ 0.13561110198497772,
+ 0.7081236839294434,
+ -0.3326506018638611,
+ 0.11330801993608475,
+ -0.0989147275686264,
+ 0.07836921513080597,
+ -0.060900237411260605,
+ 1.11102294921875,
+ -0.017686933279037476,
+ 0.029460275545716286,
+ -0.4791528880596161,
+ 0.013812395744025707,
+ -0.1606086790561676,
+ -0.02373814396560192,
+ -0.028927847743034363,
+ -0.017582418397068977,
+ -0.002322347601875663,
+ -0.009515616111457348,
+ 0.012796386145055294,
+ 0.0010435275034978986,
+ 0.0005133572849445045,
+ -0.019619032740592957,
+ 0.012490831315517426,
+ -0.012097016908228397,
+ 0.01967502385377884,
+ 0.0784754678606987,
+ -0.06453773379325867,
+ -0.00016743599553592503,
+ 1.1111270189285278,
+ 0.025668099522590637,
+ 0.23321135342121124,
+ 0.05709727853536606,
+ -0.4604215919971466,
+ -0.7881916761398315,
+ 0.26137059926986694,
+ -0.050472091883420944,
+ -0.392466276884079,
+ 0.03832476586103439,
+ 0.047914065420627594,
+ 0.004019365645945072,
+ 0.4532164931297302,
+ 0.2794245183467865,
+ -0.20846489071846008,
+ 0.008654672652482986,
+ -0.18662935495376587,
+ 0.07838035374879837
],
- "rim_k": 0.21779286861419678,
- "rim_max": 17.012699127197266
+ "rim_base": 4.0,
+ "rim_k": 0.07199979573488235,
+ "rim_max": 8.5,
+ "tint": {
+ "desaturate": 0.32,
+ "kind": "grey",
+ "shift": 0.101
+ }
},
"regular-light": {
- "bend": -1.6906808614730835,
- "blur_k": 0.14000000059604645,
- "blur_max": 12.0,
- "glow": -0.06975674629211426,
- "glow_width": 0.5,
+ "bend_base": 10.70003604888916,
+ "bend_k": 0.08199961483478546,
+ "bend_max": 26.200000762939453,
+ "blur_k": 0.25999999046325684,
+ "blur_max": 13.5,
+ "glow": 0.0010122086387127638,
+ "glow_width": 2.685718297958374,
"hairline": [
- 0.6683441400527954, 0.015820689499378204, 0.7885841131210327,
- 0.007480344735085964
+ 0.7884511947631836,
+ -0.04988262057304382,
+ 0.8663737773895264,
+ -0.03755432367324829
],
- "lens_curve": 0.5981463193893433,
- "light_angle": 5.205510139465332,
- "line": 0.01358448900282383,
- "line_lit": -0.0012929972726851702,
- "line_width": 1.5013341903686523,
+ "lens_curve": 1.0,
+ "light_angle": 0.20863288640975952,
+ "line": -0.15016056597232819,
+ "line_lit": 0.00040745738078840077,
+ "line_width": 0.30000001192092896,
"opacity": 0.6000000238418579,
"poly": [
- -0.138549342751503, 0.7256880402565002, -0.1833912432193756,
- 1.8144844770431519, -2.4605472087860107, 0.6123811602592468,
- 0.23255813121795654, 0.05579162761569023, -0.12572336196899414,
- -1.1628233194351196, 1.4883190393447876, -0.43835973739624023,
- 0.5214229226112366, -0.0343957282602787, 0.4276241362094879,
- 0.04451335221529007, -0.1150304526090622, 0.21809197962284088,
- -0.13724924623966217, 0.03976645693182945, -0.017057476565241814,
- 0.0032571046613156796, 0.050204869359731674, -0.13996750116348267,
- 0.0802760049700737, 0.5213379263877869, 0.10205833613872528,
- 0.3425259590148926, -0.017469502985477448, 0.12757959961891174,
- -1.446061372756958, 0.9996414184570312, -0.17898792028427124,
- 0.5396572947502136, -0.002463854616507888, -0.1542862057685852,
- 0.762222409248352, -0.6541531682014465, 0.5215706825256348
+ 1.2788854837417603,
+ -0.8453500866889954,
+ 0.003082971554249525,
+ 0.2738867998123169,
+ -0.27242588996887207,
+ -0.500204861164093,
+ -0.4753827750682831,
+ 1.9009149074554443,
+ -0.9198514223098755,
+ -0.7914177775382996,
+ 0.7524295449256897,
+ 0.33018216490745544,
+ 1.1248490810394287,
+ 0.14570458233356476,
+ -0.5863457918167114,
+ -1.1137068271636963,
+ 0.4047931730747223,
+ -0.5792659521102905,
+ 0.2896379828453064,
+ 0.5211592316627502,
+ -0.036302655935287476,
+ 0.41237375140190125,
+ 0.05753712356090546,
+ -0.13990472257137299,
+ 0.19397875666618347,
+ -0.044933948665857315,
+ 0.13752412796020508,
+ 0.055802471935749054,
+ -0.1938532590866089,
+ 0.07925422489643097,
+ -0.11504264175891876,
+ -0.030976055189967155,
+ -0.05894238501787186,
+ 0.06816978752613068,
+ -0.0008735256269574165,
+ -0.02404271997511387,
+ 0.12015138566493988,
+ 0.011716355569660664,
+ -0.07116328924894333,
+ 0.5211941599845886,
+ -0.599159300327301,
+ -0.7419008612632751,
+ 1.7605870962142944,
+ 0.01254228688776493,
+ 0.24147452414035797,
+ -0.6960784792900085,
+ 1.0482441186904907,
+ -0.8146082162857056,
+ 0.2614218294620514,
+ 0.20659644901752472,
+ 0.24794399738311768,
+ -0.708295464515686,
+ -0.10671452432870865,
+ -0.4012254476547241,
+ -0.5572263598442078,
+ -0.5958108305931091,
+ 0.4865833520889282,
+ 1.8127862215042114,
+ -0.43663233518600464,
+ 0.5212134122848511
],
- "rim_k": 0.2092672884464264,
- "rim_max": 15.961286544799805
+ "rim_base": 4.0,
+ "rim_k": 0.07199995219707489,
+ "rim_max": 8.5,
+ "tint": {
+ "desaturate": 0.32,
+ "kind": "grey",
+ "shift": -0.103
+ }
}
}
diff --git a/apps/desktop-gpui/glass/src/bin/glass-fit.rs b/apps/desktop-gpui/glass/src/bin/glass-fit.rs
index 2b628ba9c..445cd565a 100644
--- a/apps/desktop-gpui/glass/src/bin/glass-fit.rs
+++ b/apps/desktop-gpui/glass/src/bin/glass-fit.rs
@@ -1,9 +1,10 @@
//! Fits a `GlassMaterial` to Apple's reference captures.
//!
-//! glass-fit <reference dir> <out dir> [style-appearance ...]
+//! glass-fit <reference dir>[,<reference dir>...] <out dir> [style-appearance ...]
//!
-//! Reads `<reference dir>/manifest.json`, `scenes/*.png` and `apple/*.png`
-//! (from scripts/glass-reference) and writes `<out dir>/params.json`,
+//! Reads each `<reference dir>/manifest.json`, `scenes/*.png` and
+//! `apple/*.png` (from scripts/glass-reference: `reference` and `sweep`)
+//! and writes `<out dir>/params.json`,
//! `<out dir>/report.json` and side-by-side renders. The colour transform is
//! linear in its coefficients, so every evaluation solves it exactly by
//! least squares; Nelder-Mead only searches blur, lensing and lighting.
@@ -13,9 +14,54 @@ use std::path::{Path, PathBuf};
use cap_glass::{
Rgba, Shape, metrics,
- model::{self, GlassMaterial, POLY_TERMS},
+ model::{self, Adapt, GlassMaterial, POLY_TERMS},
};
+/// Where Regular dark glass switches between its small-pane and large-pane
+/// colour transforms, in points on the shorter side: measured from the
+/// `sweep` captures, where every pane up to 64 pt matches and every pane
+/// from 128 pt matches, with 80 pt and 96 pt on one straight line between.
+const ADAPT: [(&str, f32, f32); 1] = [("regular-dark", 64., 104.6)];
+
+/// Apple's blur sigma, `min(max, k * shorter side)`, measured from the
+/// edge in the `split` scene under the 48, 120 and 240 pt panes: a Gaussian
+/// within 0.004 of Apple's edge profile for Clear. Regular's profile has a
+/// heavier dark-side tail than any Gaussian; this is its best single fit.
+const BLUR: [(&str, f32, f32); 2] = [("clear", 0.208, 20.), ("regular", 0.26, 13.5)];
+
+/// Apple's refraction, measured from the `sweep lens` captures (UV ramp
+/// under panes from 20 to 270 pt): decay length `[base, k, max]` and edge
+/// bend `[base, k, max]`, in points of the shorter side. Light and dark
+/// match. The fit keeps these fixed.
+const LENS: [(&str, [f32; 3], [f32; 3]); 2] = [
+ ("clear", [3.5, 0.04, 7.9], [0., 0.522, 44.7]),
+ ("regular", [4., 0.072, 8.5], [10.7, 0.082, 26.2]),
+];
+
+fn with_lens(preset: &str, material: GlassMaterial) -> GlassMaterial {
+ let (_, rim, bend) = LENS
+ .iter()
+ .find(|(style, ..)| preset.starts_with(style))
+ .expect("every preset has a measured lens");
+ GlassMaterial {
+ rim_base: rim[0],
+ rim_k: rim[1],
+ rim_max: rim[2],
+ bend_base: bend[0],
+ bend_k: bend[1],
+ bend_max: bend[2],
+ lens_curve: 1.,
+ ..material
+ }
+}
+
+fn adapt_for(preset: &str, poly: [f32; 3 * POLY_TERMS]) -> Option<Adapt> {
+ ADAPT
+ .iter()
+ .find(|(name, ..)| *name == preset)
+ .map(|&(_, small, large)| Adapt { small, large, poly })
+}
+
#[derive(serde::Deserialize)]
struct Manifest {
shapes: Vec<ManifestShape>,
@@ -53,12 +99,16 @@ struct Case {
style: String,
appearance: String,
tint: String,
+ /// The sweep's falling pass repeats its rising one.
+ #[serde(default)]
+ pass: String,
}
struct Sample {
name: String,
backdrop: Rgba,
apple: Rgba,
+ shapes: Vec<Shape>,
/// One blurred crop per shape: (origin x, origin y, crop).
crops: Vec<(usize, usize, Rgba)>,
}
@@ -70,24 +120,25 @@ const NEUTRAL_WEIGHT: f64 = 12.;
fn main() {
let args: Vec<String> = std::env::args().collect();
- let reference = PathBuf::from(&args[1]);
+ let references: Vec<(PathBuf, Manifest)> = args[1]
+ .split(',')
+ .map(|dir| {
+ let dir = PathBuf::from(dir);
+ let manifest =
+ serde_json::from_slice(&std::fs::read(dir.join("manifest.json")).unwrap()).unwrap();
+ (dir, manifest)
+ })
+ .collect();
let out = PathBuf::from(&args[2]);
std::fs::create_dir_all(out.join("renders")).unwrap();
- let manifest: Manifest =
- serde_json::from_slice(&std::fs::read(reference.join("manifest.json")).unwrap()).unwrap();
- let scale = manifest.scale;
+ let scale = references[0].1.scale;
+ assert!(
+ references
+ .iter()
+ .all(|(_, manifest)| manifest.scale == scale),
+ "references must share a backing scale"
+ );
SCALE.set(scale).unwrap();
- let shapes: Vec<Shape> = manifest
- .shapes
- .iter()
- .map(|shape| Shape {
- x: shape.rect[0] * scale,
- y: shape.rect[1] * scale,
- width: shape.rect[2] * scale,
- height: shape.rect[3] * scale,
- radius: shape.radius * scale,
- })
- .collect();
let presets: Vec<String> = if args.len() > 3 {
args[3..].to_vec()
} else {
@@ -95,6 +146,9 @@ fn main() {
.map(String::from)
.to_vec()
};
+ // `GLASS_ALL_GREYS=1` scores every level of the sweep; the search uses
+ // every other one, which pins the tone curve as well at half the cost.
+ let all_greys = std::env::var_os("GLASS_ALL_GREYS").is_some();
let fixed: Option<serde_json::Value> = std::env::var("GLASS_PARAMS")
.ok()
.and_then(|path| serde_json::from_slice(&std::fs::read(path).ok()?).ok());
@@ -102,77 +156,171 @@ fn main() {
let mut fitted = serde_json::Map::new();
let mut report = serde_json::Map::new();
for preset in presets {
- let mut samples: Vec<Sample> = manifest
- .cases
+ let mut samples: Vec<Sample> = references
.iter()
- .filter(|case| {
- format!("{}-{}", case.style, case.appearance) == preset
- && case.tint == "none"
- && case.scene != "uvfine"
- })
- .map(|case| Sample {
- name: case.name.clone(),
- backdrop: Rgba::load(&reference.join(format!("scenes/{}.png", case.scene))).unwrap(),
- apple: Rgba::load(&reference.join(format!("apple/{}.png", case.name))).unwrap(),
- crops: Vec::new(),
+ .flat_map(|(reference, manifest)| {
+ let shapes: Vec<Shape> = manifest
+ .shapes
+ .iter()
+ .map(|shape| Shape {
+ x: shape.rect[0] * scale,
+ y: shape.rect[1] * scale,
+ width: shape.rect[2] * scale,
+ height: shape.rect[3] * scale,
+ radius: shape.radius * scale,
+ })
+ .collect();
+ manifest
+ .cases
+ .iter()
+ .filter(|case| {
+ format!("{}-{}", case.style, case.appearance) == preset
+ && case.tint == "none"
+ && case.scene != "uvfine"
+ && case.pass != "down"
+ && (all_greys || sweep_level_kept(&case.scene))
+ })
+ .map(move |case| Sample {
+ name: case.name.clone(),
+ backdrop: Rgba::load(&reference.join(format!("scenes/{}.png", case.scene)))
+ .unwrap(),
+ apple: Rgba::load(&reference.join(format!("apple/{}.png", case.name)))
+ .unwrap(),
+ shapes: shapes.clone(),
+ crops: Vec::new(),
+ })
+ .collect::<Vec<_>>()
})
.collect();
let material = match fixed
.as_ref()
.and_then(|all| serde_json::from_value::<GlassMaterial>(all.get(&preset)?.clone()).ok())
- {
+ .map(|material| GlassMaterial {
+ adapt: material.adapt.or_else(|| adapt_for(&preset, material.poly)),
+ ..material
+ }) {
// `GLASS_RESOLVE=1`: keep the given blur, lensing and lighting but
// solve the colour transform again.
Some(material) if std::env::var_os("GLASS_RESOLVE").is_some() => {
- prepare(&mut samples, &shapes, &material);
- let (loss, material) = evaluate(&material, &shapes, &samples);
+ prepare(&mut samples, &material);
+ let (loss, material) = evaluate(&material, &samples);
eprintln!("{preset}: re-solved colour, loss {loss:.2}");
material
}
Some(material) => material,
- None => fit(&preset, &mut samples, &shapes),
+ None => fit(&preset, &mut samples),
};
eprintln!("{preset}:\n{material:#?}");
- prepare(&mut samples, &shapes, &material);
- let mask = region_mask(&shapes, &samples[0].backdrop);
+ prepare(&mut samples, &material);
let mut scores = serde_json::Map::new();
for sample in &samples {
- let rendered = render_sample(&material, &shapes, sample);
+ let mask = region_mask(&sample.shapes, &sample.backdrop);
+ let rendered = render_sample(&material, sample);
let ssim = metrics::ssim(&rendered, &sample.apple, &mask);
let (mean, p95) = metrics::delta_e(&rendered, &sample.apple, &mask);
scores.insert(
sample.name.clone(),
serde_json::json!({ "ssim": ssim, "deltaE": mean, "deltaE95": p95 }),
);
- side_by_side(&rendered, &sample.apple, &out.join(format!("renders/{}.png", sample.name)));
+ side_by_side(
+ &rendered,
+ &sample.apple,
+ &out.join(format!("renders/{}.png", sample.name)),
+ );
}
fitted.insert(preset.clone(), serde_json::to_value(material).unwrap());
report.insert(preset, serde_json::Value::Object(scores));
- std::fs::write(out.join("params.json"), serde_json::to_string_pretty(&fitted).unwrap()).unwrap();
- std::fs::write(out.join("report.json"), serde_json::to_string_pretty(&report).unwrap()).unwrap();
+ std::fs::write(
+ out.join("params.json"),
+ serde_json::to_string_pretty(&fitted).unwrap(),
+ )
+ .unwrap();
+ std::fs::write(
+ out.join("report.json"),
+ serde_json::to_string_pretty(&report).unwrap(),
+ )
+ .unwrap();
}
}
-fn fit(preset: &str, samples: &mut [Sample], shapes: &[Shape]) -> GlassMaterial {
- let start = GlassMaterial {
- blur_k: 0.19,
- blur_max: 21.,
- rim_k: 0.24,
- rim_max: 24.,
- bend: -2.,
- lens_curve: 0.4,
- poly: [0.; 3 * POLY_TERMS],
- opacity: 0.6,
- line: 0.,
- line_lit: 0.,
- line_width: 1.,
- light_angle: -2.3,
- glow: 0.,
- glow_width: 4.,
- hairline: [0.85, -0.12, 0.9, -0.08],
- };
+/// `GLASS_NEUTRAL_WEIGHT` and `GLASS_SWEEP_WEIGHT` override how much the
+/// flat scenes and the sweep's greys count in the colour fit.
+fn neutral_weight() -> f64 {
+ std::env::var("GLASS_NEUTRAL_WEIGHT")
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(NEUTRAL_WEIGHT)
+}
+
+fn sweep_weight() -> f64 {
+ std::env::var("GLASS_SWEEP_WEIGHT")
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(1.)
+}
+
+/// The sweep's greys the search uses: every 32 levels, plus white.
+fn sweep_level_kept(scene: &str) -> bool {
+ scene
+ .strip_prefix("grey")
+ .and_then(|level| level.parse::<u32>().ok())
+ .is_none_or(|level| level % 32 == 0 || level == 255)
+}
+
+fn fit(preset: &str, samples: &mut [Sample]) -> GlassMaterial {
+ let start = with_lens(
+ preset,
+ GlassMaterial {
+ blur_k: 0.19,
+ blur_max: 21.,
+ rim_base: 0.,
+ rim_k: 0.,
+ rim_max: 0.,
+ bend_base: 0.,
+ bend_k: 0.,
+ bend_max: 0.,
+ lens_curve: 1.,
+ poly: [0.; 3 * POLY_TERMS],
+ opacity: 0.6,
+ line: 0.,
+ line_lit: 0.,
+ line_width: 1.,
+ light_angle: -2.3,
+ glow: 0.,
+ glow_width: 4.,
+ hairline: [0.85, -0.12, 0.9, -0.08],
+ adapt: adapt_for(preset, [0.; 3 * POLY_TERMS]),
+ tint: None,
+ },
+ );
+ if std::env::var_os("GLASS_SEARCH_BLUR").is_none() {
+ // `GLASS_BLUR=<k>,<max>` overrides the measured law.
+ let &(_, measured_k, measured_max) = BLUR
+ .iter()
+ .find(|(style, ..)| preset.starts_with(style))
+ .expect("every preset has a measured blur");
+ let (blur_k, blur_max) = std::env::var("GLASS_BLUR")
+ .ok()
+ .and_then(|law| {
+ let (k, max) = law.split_once(',')?;
+ Some((k.parse().ok()?, max.parse().ok()?))
+ })
+ .unwrap_or((measured_k, measured_max));
+ let (loss, material) = fit_at_law(
+ samples,
+ GlassMaterial {
+ blur_k,
+ blur_max,
+ ..start
+ },
+ );
+ eprintln!(
+ "{preset}: measured blur {blur_k:.3} x side, max {blur_max:.1} -> loss {loss:.2}"
+ );
+ return material;
+ }
let mut best: Option<(f64, GlassMaterial)> = None;
let mut try_law = |blur_k: f32, blur_max: f32, best: &mut Option<(f64, GlassMaterial)>| {
let seed = GlassMaterial {
@@ -180,7 +328,7 @@ fn fit(preset: &str, samples: &mut [Sample], shapes: &[Shape]) -> GlassMaterial
blur_max,
..best.map_or(start, |(_, material)| material)
};
- let (loss, material) = fit_at_law(samples, shapes, seed);
+ let (loss, material) = fit_at_law(samples, seed);
eprintln!("{preset}: blur {blur_k:.3} x side, max {blur_max:.1} -> loss {loss:.2}");
if best.is_none_or(|(current, _)| loss < current) {
*best = Some((loss, material));
@@ -196,7 +344,11 @@ fn fit(preset: &str, samples: &mut [Sample], shapes: &[Shape]) -> GlassMaterial
for _ in 0..2 {
let law = best.unwrap().1;
for (dk, dm) in [(-0.02, 0.), (0.02, 0.), (0., -2.), (0., 2.)] {
- try_law((law.blur_k + dk).max(0.01), (law.blur_max + dm).max(1.), &mut best);
+ try_law(
+ (law.blur_k + dk).max(0.01),
+ (law.blur_max + dm).max(1.),
+ &mut best,
+ );
}
}
best.unwrap().1
@@ -212,19 +364,22 @@ fn crop(image: &Rgba, x0: usize, y0: usize, x1: usize, y1: usize) -> Rgba {
out
}
-fn prepare(samples: &mut [Sample], shapes: &[Shape], material: &GlassMaterial) {
+fn prepare(samples: &mut [Sample], material: &GlassMaterial) {
std::thread::scope(|scope| {
for sample in samples.iter_mut() {
scope.spawn(move || {
- sample.crops = shapes
+ sample.crops = sample
+ .shapes
.iter()
.map(|shape| {
let blur = style_for(material, shape).blur;
let pad = PAD * SCALE.get().unwrap_or(&1.) + blur * 3.;
let x0 = (shape.x - pad).max(0.) as usize;
let y0 = (shape.y - pad).max(0.) as usize;
- let x1 = ((shape.x + shape.width + pad) as usize).min(sample.backdrop.width);
- let y1 = ((shape.y + shape.height + pad) as usize).min(sample.backdrop.height);
+ let x1 =
+ ((shape.x + shape.width + pad) as usize).min(sample.backdrop.width);
+ let y1 =
+ ((shape.y + shape.height + pad) as usize).min(sample.backdrop.height);
(x0, y0, crop(&sample.backdrop, x0, y0, x1, y1).blurred(blur))
})
.collect();
@@ -233,18 +388,22 @@ fn prepare(samples: &mut [Sample], shapes: &[Shape], material: &GlassMaterial) {
});
}
-/// Visit glass pixels with their global position and weight. With `sparse`,
-/// pixels deeper than 12 px inside are visited on every other row and
-/// column at four times the weight: they carry far less than the rim does.
+/// Visit glass pixels with their global position, weight and how much of
+/// the small-pane colour transform their pane uses. With `sparse`, pixels
+/// deeper than 12 px inside are visited on every other row and column at
+/// four times the weight: they carry far less than the rim does.
fn for_each_glass_pixel(
material: &GlassMaterial,
- shapes: &[Shape],
sample: &Sample,
sparse: bool,
- mut visit: impl FnMut(&model::GlassSample, &model::PaneStyle, usize, usize, f64),
+ mut visit: impl FnMut(&model::GlassSample, &model::PaneStyle, usize, usize, f64, f32),
) {
- for (shape, (ox, oy, blurred)) in shapes.iter().zip(&sample.crops) {
+ let scale = *SCALE.get().unwrap_or(&1.);
+ for (shape, (ox, oy, blurred)) in sample.shapes.iter().zip(&sample.crops) {
let style = style_for(material, shape);
+ let small = material.adapt.map_or(0., |adapt| {
+ adapt.weight(shape.width.min(shape.height) / scale)
+ });
let local = Shape {
x: shape.x - *ox as f32,
y: shape.y - *oy as f32,
@@ -267,21 +426,26 @@ fn for_each_glass_pixel(
};
let glass = model::sample(&style, &local, blurred, px, py);
if glass.coverage > 0. || glass.ring > 0. {
- visit(&glass, &style, x + ox, y + oy, weight);
+ visit(&glass, &style, x + ox, y + oy, weight, small);
}
}
}
}
}
-fn render_sample(material: &GlassMaterial, shapes: &[Shape], sample: &Sample) -> Rgba {
+fn render_sample(material: &GlassMaterial, sample: &Sample) -> Rgba {
let mut out = sample.backdrop.clone();
- for_each_glass_pixel(material, shapes, sample, false, |glass, style, x, y, _| {
+ for_each_glass_pixel(material, sample, false, |glass, style, x, y, _, _| {
let under = sample.backdrop.get(x, y);
let under =
model::under_with_hairline(glass, [under[0] / 255., under[1] / 255., under[2] / 255.]);
- let color = if glass.coverage > 0. { model::finish(style, glass) } else { under };
- let mix = |i: usize| (under[i] + (color[i].clamp(0., 1.) - under[i]) * glass.coverage) * 255.;
+ let color = if glass.coverage > 0. {
+ model::finish(style, glass)
+ } else {
+ under
+ };
+ let mix =
+ |i: usize| (under[i] + (color[i].clamp(0., 1.) - under[i]) * glass.coverage) * 255.;
out.set(x, y, [mix(0), mix(1), mix(2), 255.]);
});
out
@@ -289,10 +453,14 @@ fn render_sample(material: &GlassMaterial, shapes: &[Shape], sample: &Sample) ->
/// Normal equations of the colour transform over every covered pixel:
/// `coverage * scale * features . poly = target - (1 - coverage) * under -
-/// coverage * glow`, per channel, plus what the residual needs.
+/// coverage * glow`, per channel, plus what the residual needs. With size
+/// adaptation the features come twice, weighted by how much of the large-
+/// and the small-pane transform the pixel's pane uses, so both are solved
+/// together.
struct Normal {
- ata: [[f64; POLY_TERMS]; POLY_TERMS],
- atb: [[f64; 3]; POLY_TERMS],
+ terms: usize,
+ ata: Vec<f64>,
+ atb: Vec<[f64; 3]>,
btb: [f64; 3],
count: usize,
/// Squared error of hairline-only pixels, which the transform cannot
@@ -302,10 +470,11 @@ struct Normal {
}
impl Normal {
- fn new() -> Self {
+ fn new(terms: usize) -> Self {
Self {
- ata: [[0.; POLY_TERMS]; POLY_TERMS],
- atb: [[0.; 3]; POLY_TERMS],
+ terms,
+ ata: vec![0.; terms * terms],
+ atb: vec![[0.; 3]; terms],
btb: [0.; 3],
count: 0,
fixed_sse: 0.,
@@ -314,12 +483,12 @@ impl Normal {
}
fn add(&mut self, other: &Self) {
- for i in 0..POLY_TERMS {
- for j in 0..POLY_TERMS {
- self.ata[i][j] += other.ata[i][j];
- }
+ for (a, b) in self.ata.iter_mut().zip(&other.ata) {
+ *a += b;
+ }
+ for (a, b) in self.atb.iter_mut().zip(&other.atb) {
for c in 0..3 {
- self.atb[i][c] += other.atb[i][c];
+ a[c] += b[c];
}
}
for c in 0..3 {
@@ -330,119 +499,150 @@ impl Normal {
self.fixed_count += other.fixed_count;
}
- /// Least-squares coefficients and the mean squared error per channel
- /// value on the 0-255 scale.
- fn solve(&self) -> ([f32; 3 * POLY_TERMS], f64) {
- let mut a = self.ata;
- for (i, row) in a.iter_mut().enumerate() {
- row[i] += 1e-6;
+ /// Least-squares coefficients, `terms` per channel, and the mean
+ /// squared error per channel value on the 0-255 scale.
+ fn solve(&self) -> (Vec<[f32; 3]>, f64) {
+ let n = self.terms;
+ let mut a = self.ata.clone();
+ for i in 0..n {
+ a[i * n + i] += 1e-6;
}
- let mut poly = [0f32; 3 * POLY_TERMS];
+ let mut coefficients = vec![[0f32; 3]; n];
let mut sse = 0.;
for c in 0..3 {
- let b: [f64; POLY_TERMS] = std::array::from_fn(|i| self.atb[i][c]);
- let x = solve_linear(a, b);
+ let b: Vec<f64> = self.atb.iter().map(|row| row[c]).collect();
+ let x = solve_linear(a.clone(), b.clone(), n);
let mut xax = 0.;
let mut xb = 0.;
- for i in 0..POLY_TERMS {
- poly[c * POLY_TERMS + i] = x[i] as f32;
+ for i in 0..n {
+ coefficients[i][c] = x[i] as f32;
xb += x[i] * b[i];
- for j in 0..POLY_TERMS {
- xax += x[i] * self.ata[i][j] * x[j];
+ for j in 0..n {
+ xax += x[i] * self.ata[i * n + j] * x[j];
}
}
sse += self.btb[c] - 2. * xb + xax;
}
let total = sse.max(0.) + self.fixed_sse;
let values = 3 * (self.count + self.fixed_count).max(1);
- (poly, total / values as f64 * 255. * 255.)
+ (coefficients, total / values as f64 * 255. * 255.)
}
}
-fn solve_linear(
- mut m: [[f64; POLY_TERMS]; POLY_TERMS],
- mut v: [f64; POLY_TERMS],
-) -> [f64; POLY_TERMS] {
- for col in 0..POLY_TERMS {
- let pivot = (col..POLY_TERMS)
- .max_by(|a, b| m[*a][col].abs().total_cmp(&m[*b][col].abs()))
+fn solve_linear(mut m: Vec<f64>, mut v: Vec<f64>, n: usize) -> Vec<f64> {
+ for col in 0..n {
+ let pivot = (col..n)
+ .max_by(|a, b| m[*a * n + col].abs().total_cmp(&m[*b * n + col].abs()))
.unwrap();
- m.swap(col, pivot);
+ for k in 0..n {
+ m.swap(col * n + k, pivot * n + k);
+ }
v.swap(col, pivot);
- for row in 0..POLY_TERMS {
- if row != col && m[col][col] != 0. {
- let factor = m[row][col] / m[col][col];
- for k in 0..POLY_TERMS {
- m[row][k] -= factor * m[col][k];
+ for row in 0..n {
+ if row != col && m[col * n + col] != 0. {
+ let factor = m[row * n + col] / m[col * n + col];
+ for k in 0..n {
+ m[row * n + k] -= factor * m[col * n + k];
}
v[row] -= factor * v[col];
}
}
}
- std::array::from_fn(|i| if m[i][i] == 0. { 0. } else { v[i] / m[i][i] })
+ (0..n)
+ .map(|i| {
+ if m[i * n + i] == 0. {
+ 0.
+ } else {
+ v[i] / m[i * n + i]
+ }
+ })
+ .collect()
}
-fn normal_equations(material: &GlassMaterial, shapes: &[Shape], samples: &[Sample]) -> Normal {
+fn normal_equations(material: &GlassMaterial, samples: &[Sample]) -> Normal {
+ let blocks = if material.adapt.is_some() { 2 } else { 1 };
+ let terms = POLY_TERMS * blocks;
std::thread::scope(|scope| {
let handles: Vec<_> = samples
.iter()
.map(|sample| {
scope.spawn(move || {
- let mut normal = Normal::new();
+ let mut normal = Normal::new(terms);
// Flat backdrops pin the grey axis, where any error shows
// most; a handful of colourful scenes would otherwise
// outvote them.
let neutral = ["white-", "black-", "gray-"]
.iter()
.any(|prefix| sample.name.starts_with(prefix));
- let scene_weight = if neutral { NEUTRAL_WEIGHT } else { 1. };
- for_each_glass_pixel(material, shapes, sample, true, |glass, _, x, y, weight| {
- let weight = weight * scene_weight;
- let under = sample.backdrop.get(x, y);
- let under = model::under_with_hairline(
- glass,
- [under[0] / 255., under[1] / 255., under[2] / 255.],
- );
- let target = sample.apple.get(x, y);
- if glass.coverage <= 0. {
- for c in 0..3 {
- let error = under[c] as f64 - target[c] as f64 / 255.;
- normal.fixed_sse += weight * error * error;
- }
- normal.fixed_count += weight as usize;
- return;
- }
- let features = model::poly_features(glass.source);
- let scale = (glass.coverage * glass.scale) as f64;
- let row: [f64; POLY_TERMS] =
- std::array::from_fn(|i| features[i] as f64 * scale);
- for i in 0..POLY_TERMS {
- for j in i..POLY_TERMS {
- normal.ata[i][j] += weight * row[i] * row[j];
+ let scene_weight = if neutral { neutral_weight() } else { 1. }
+ * if sample.name.starts_with("grey") {
+ sweep_weight()
+ } else {
+ 1.
+ };
+ let mut row = vec![0f64; terms];
+ for_each_glass_pixel(
+ material,
+ sample,
+ true,
+ |glass, _, x, y, weight, small| {
+ let weight = weight * scene_weight;
+ let under = sample.backdrop.get(x, y);
+ let under = model::under_with_hairline(
+ glass,
+ [under[0] / 255., under[1] / 255., under[2] / 255.],
+ );
+ let target = sample.apple.get(x, y);
+ if glass.coverage <= 0. {
+ for c in 0..3 {
+ let error = under[c] as f64 - target[c] as f64 / 255.;
+ normal.fixed_sse += weight * error * error;
+ }
+ normal.fixed_count += weight as usize;
+ return;
}
- }
- let coverage = glass.coverage as f64;
- for c in 0..3 {
- let b = target[c] as f64 / 255.
- - (1. - coverage) * under[c] as f64
- - coverage * glass.glow as f64;
+ let features = model::poly_features(glass.source);
+ let scale = (glass.coverage * glass.scale) as f64;
for i in 0..POLY_TERMS {
- normal.atb[i][c] += weight * row[i] * b;
+ let feature = features[i] as f64 * scale;
+ if blocks == 1 {
+ row[i] = feature;
+ } else {
+ row[i] = feature * (1. - small as f64);
+ row[POLY_TERMS + i] = feature * small as f64;
+ }
}
- normal.btb[c] += weight * b * b;
- }
- normal.count += weight as usize;
- });
- for i in 0..POLY_TERMS {
+ for i in 0..terms {
+ if row[i] == 0. {
+ continue;
+ }
+ for j in i..terms {
+ normal.ata[i * terms + j] += weight * row[i] * row[j];
+ }
+ }
+ let coverage = glass.coverage as f64;
+ for c in 0..3 {
+ let b = target[c] as f64 / 255.
+ - (1. - coverage) * under[c] as f64
+ - coverage * glass.glow as f64;
+ for i in 0..terms {
+ normal.atb[i][c] += weight * row[i] * b;
+ }
+ normal.btb[c] += weight * b * b;
+ }
+ normal.count += weight as usize;
+ },
+ );
+ for i in 0..terms {
for j in 0..i {
- normal.ata[i][j] = normal.ata[j][i];
+ normal.ata[i * terms + j] = normal.ata[j * terms + i];
}
}
normal
})
})
.collect();
- let mut total = Normal::new();
+ let mut total = Normal::new(terms);
for handle in handles {
total.add(&handle.join().unwrap());
}
@@ -450,23 +650,30 @@ fn normal_equations(material: &GlassMaterial, shapes: &[Shape], samples: &[Sampl
})
}
-fn evaluate(material: &GlassMaterial, shapes: &[Shape], samples: &[Sample]) -> (f64, GlassMaterial) {
- let (poly, loss) = normal_equations(material, shapes, samples).solve();
- (loss, GlassMaterial { poly, ..*material })
+fn evaluate(material: &GlassMaterial, samples: &[Sample]) -> (f64, GlassMaterial) {
+ let (coefficients, loss) = normal_equations(material, samples).solve();
+ let mut material = *material;
+ for c in 0..3 {
+ for i in 0..POLY_TERMS {
+ material.poly[c * POLY_TERMS + i] = coefficients[i][c];
+ if let Some(adapt) = &mut material.adapt {
+ adapt.poly[c * POLY_TERMS + i] = coefficients[POLY_TERMS + i][c];
+ }
+ }
+ }
+ (loss, material)
}
/// Fit everything but the blur law, which stays fixed so each backdrop is
/// blurred once.
-fn fit_at_law(
- samples: &mut [Sample],
- shapes: &[Shape],
- start: GlassMaterial,
-) -> (f64, GlassMaterial) {
- prepare(samples, shapes, &start);
+fn fit_at_law(samples: &mut [Sample], start: GlassMaterial) -> (f64, GlassMaterial) {
+ prepare(samples, &start);
let samples: &[Sample] = samples;
- let objective = |values: &[f32]| evaluate(&start.with_shape(values), shapes, samples).0;
+ let objective = |values: &[f32]| evaluate(&start.with_shape(values), samples).0;
+ // Blur is searched outside, the lens is measured: only lighting and the
+ // edge line move here.
let scales = [
- 0., 0., 0.05, 6., 0.6, 0.2, 0.04, 0.04, 0.5, 0.8, 0.04, 3., 0.08, 0.05, 0.08, 0.05,
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.04, 0.04, 0.5, 0.8, 0.04, 3., 0.08, 0.05, 0.08, 0.05,
];
let mut point = start.shape_vec().to_vec();
let mut value = objective(&point);
@@ -478,13 +685,16 @@ fn fit_at_law(
value = next_value;
point = next;
}
- evaluate(&start.with_shape(&point), shapes, samples)
+ evaluate(&start.with_shape(&point), samples)
}
fn region_mask(shapes: &[Shape], image: &Rgba) -> Vec<bool> {
(0..image.width * image.height)
.map(|index| {
- let (x, y) = ((index % image.width) as f32 + 0.5, (index / image.width) as f32 + 0.5);
+ let (x, y) = (
+ (index % image.width) as f32 + 0.5,
+ (index / image.width) as f32 + 0.5,
+ );
shapes.iter().any(|shape| shape.sdf(x, y) < 1.5)
})
.collect()
@@ -536,8 +746,11 @@ fn nelder_mead(
} else {
let best = simplex[0].1.clone();
for vertex in simplex.iter_mut().skip(1) {
- let shrunk: Vec<f32> =
- best.iter().zip(&vertex.1).map(|(b, v)| b + 0.5 * (v - b)).collect();
+ let shrunk: Vec<f32> = best
+ .iter()
+ .zip(&vertex.1)
+ .map(|(b, v)| b + 0.5 * (v - b))
+ .collect();
*vertex = (objective(&shrunk), shrunk);
}
}
diff --git a/apps/desktop-gpui/glass/src/model.rs b/apps/desktop-gpui/glass/src/model.rs
index c767ea06a..4af498f96 100644
--- a/apps/desktop-gpui/glass/src/model.rs
+++ b/apps/desktop-gpui/glass/src/model.rs
@@ -1,10 +1,12 @@
use crate::{Rgba, Shape};
-/// Terms of the colour transform, per output channel:
-/// `r, g, b, r², g², b², rg, gb, rb, r³, g³, b³, 1` of the blurred backdrop
-/// (0-1 sRGB). The cubes let it follow Apple's tone curve along the grey
-/// axis, which a quadratic misses by several levels at mid grey.
-pub const POLY_TERMS: usize = 13;
+/// Terms of the colour transform, per output channel: the full cubic in
+/// `r, g, b` of the blurred backdrop (0-1 sRGB), constant last. The cubes
+/// follow Apple's tone curve along the grey axis; the mixed cubic terms let
+/// that curve act on brightness without bending hue, which Apple's Regular
+/// glass needs over saturated content (it lifts a light blue's blue channel
+/// past what white comes out as).
+pub const POLY_TERMS: usize = 20;
pub fn poly_features(c: [f32; 3]) -> [f32; POLY_TERMS] {
let [r, g, b] = c;
@@ -21,6 +23,13 @@ pub fn poly_features(c: [f32; 3]) -> [f32; POLY_TERMS] {
r * r * r,
g * g * g,
b * b * b,
+ r * r * g,
+ r * r * b,
+ g * g * r,
+ g * g * b,
+ b * b * r,
+ b * b * g,
+ r * g * b,
1.,
]
}
@@ -33,13 +42,20 @@ pub struct GlassMaterial {
/// Blur sigma: `min(blur_max, blur_k * shorter side)`.
pub blur_k: f32,
pub blur_max: f32,
- /// Width of the lensing rim: `min(rim_max, rim_k * shorter side)`.
+ /// Decay length of the lensing rim:
+ /// `min(rim_max, rim_base + rim_k * shorter side)`.
+ pub rim_base: f32,
pub rim_k: f32,
pub rim_max: f32,
- /// How far the rim bends light along the normal, in rim widths
- /// (negative pulls from inside the pane).
- pub bend: f32,
- /// Exponent of the bend's falloff across the rim.
+ /// How far the edge pulls light in from inside the pane:
+ /// `min(bend_max, bend_base + bend_k * shorter side)`. Apple's grows with
+ /// the pane up to a cap, independently of the decay length.
+ pub bend_base: f32,
+ pub bend_k: f32,
+ pub bend_max: f32,
+ /// Shape of the falloff: the bend at depth `d` is
+ /// `exp(-(d / decay)^lens_curve)` of the edge's, so 1 is the
+ /// exponential falloff Apple's captures follow.
pub lens_curve: f32,
/// Second-order colour transform of the blurred backdrop: for each output
/// channel, coefficients of [`poly_features`]. It carries the frost, the
@@ -64,6 +80,153 @@ pub struct GlassMaterial {
/// between vertical edges (`[a, b]` first) and horizontal ones by the
/// edge normal.
pub hairline: [f32; 4],
+ /// Size adaptation: Regular glass in dark mode lifts small panes over
+ /// bright content.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub adapt: Option<Adapt>,
+ /// How a tint colours this material.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tint: Option<TintLaw>,
+}
+
+/// Rec. 709 luma of a gamma-encoded colour: the weights Apple's tint mixes
+/// with, which fit its captures better than Rec. 601 or linear light.
+pub const LUMA: [f32; 3] = [0.2126, 0.7152, 0.0722];
+
+/// How a tint (an sRGB colour and an alpha) changes the finished glass
+/// colour `u`, measured from Apple's tinted glass (`sweep tints` and
+/// `sweep levels`). Either way it comes down to a colour matrix,
+/// `u * scale + luma(u) * luma + offset` per channel: see [`TintMatrix`].
+#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum TintLaw {
+ /// Regular glass ignores the tint's colour: it mixes `desaturate *
+ /// alpha` of the way towards the luma and shifts by `shift * alpha`.
+ Grey { desaturate: f32, shift: f32 },
+ /// Clear glass alpha-blends a tint layer in sRGB. The layer is the tint
+ /// itself over white and a darker, more saturated colour of the same hue
+ /// over black, following the luma in between. Over black, the tint's
+ /// brightest and darkest channels land on `high` and `low`, looked up by
+ /// the tint's HSL lightness (rows, [`TINT_LIGHTNESS`]) and saturation
+ /// (columns, [`TINT_SATURATION`]); the other channel keeps its place
+ /// between them. Values below 0 are kept: they clamp per channel.
+ Layer {
+ high: [[f32; 5]; 12],
+ low: [[f32; 5]; 12],
+ },
+}
+
+/// The HSL grid Clear's tint table is measured on (`sweep hsl`).
+pub const TINT_LIGHTNESS: [f32; 12] = [0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.];
+pub const TINT_SATURATION: [f32; 5] = [0., 0.25, 0.5, 0.75, 1.];
+
+/// Bilinear lookup in a table over [`TINT_LIGHTNESS`] x [`TINT_SATURATION`].
+fn tint_lookup(table: &[[f32; 5]; 12], lightness: f32, saturation: f32) -> f32 {
+ fn cell(axis: &[f32], value: f32) -> (usize, f32) {
+ let value = value.clamp(axis[0], axis[axis.len() - 1]);
+ let index = axis
+ .windows(2)
+ .position(|pair| value <= pair[1])
+ .unwrap_or(axis.len() - 2);
+ (
+ index,
+ (value - axis[index]) / (axis[index + 1] - axis[index]),
+ )
+ }
+ let (row, along_l) = cell(&TINT_LIGHTNESS, lightness);
+ let (column, along_s) = cell(&TINT_SATURATION, saturation);
+ let mix = |a: f32, b: f32, t: f32| a + (b - a) * t;
+ mix(
+ mix(table[row][column], table[row][column + 1], along_s),
+ mix(table[row + 1][column], table[row + 1][column + 1], along_s),
+ along_l,
+ )
+}
+
+/// A tint resolved to what the renderers apply to the finished colour.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct TintMatrix {
+ pub scale: [f32; 3],
+ pub luma: [f32; 3],
+ pub offset: [f32; 3],
+}
+
+impl TintMatrix {
+ pub const NONE: Self = Self {
+ scale: [1.; 3],
+ luma: [0.; 3],
+ offset: [0.; 3],
+ };
+
+ pub fn apply(&self, u: [f32; 3]) -> [f32; 3] {
+ let y = u[0] * LUMA[0] + u[1] * LUMA[1] + u[2] * LUMA[2];
+ std::array::from_fn(|c| u[c] * self.scale[c] + y * self.luma[c] + self.offset[c])
+ }
+}
+
+impl TintLaw {
+ /// `color` is sRGB 0-1, `alpha` 0-1.
+ pub fn matrix(&self, color: [f32; 3], alpha: f32) -> TintMatrix {
+ let alpha = alpha.clamp(0., 1.);
+ match *self {
+ TintLaw::Grey { desaturate, shift } => {
+ let mix = desaturate * alpha;
+ TintMatrix {
+ scale: [1. - mix; 3],
+ luma: [mix; 3],
+ offset: [shift * alpha; 3],
+ }
+ }
+ TintLaw::Layer { high, low } => {
+ let t = color.map(|c| c.clamp(0., 1.));
+ let (brightest, darkest) = (t[0].max(t[1]).max(t[2]), t[0].min(t[1]).min(t[2]));
+ let lightness = (brightest + darkest) / 2.;
+ let spread = 1. - (2. * lightness - 1.).abs();
+ let saturation = if spread > 1e-6 {
+ (brightest - darkest) / spread
+ } else {
+ 0.
+ };
+ let (to_high, to_low) = (
+ tint_lookup(&high, lightness, saturation),
+ tint_lookup(&low, lightness, saturation),
+ );
+ let over_black = t.map(|c| {
+ let place = if brightest - darkest > 1e-6 {
+ (c - darkest) / (brightest - darkest)
+ } else {
+ 0.5
+ };
+ (to_low + (to_high - to_low) * place).clamp(0., 1.)
+ });
+ TintMatrix {
+ scale: [1. - alpha; 3],
+ luma: std::array::from_fn(|c| alpha * (t[c] - over_black[c])),
+ offset: over_black.map(|n| alpha * n),
+ }
+ }
+ }
+ }
+}
+
+/// A second colour transform for small panes. Below `small` points on the
+/// shorter side a pane uses `poly`, above `large` the material's own, and
+/// in between a linear blend of the two. Apple's captures show no
+/// dependence on the backdrop beyond the transform itself, and no
+/// hysteresis, so the blend is fixed per pane size.
+#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct Adapt {
+ pub small: f32,
+ pub large: f32,
+ #[serde(with = "serde_poly")]
+ pub poly: [f32; 3 * POLY_TERMS],
+}
+
+impl Adapt {
+ /// How much of the small-pane transform a pane uses.
+ pub fn weight(&self, shorter: f32) -> f32 {
+ ((self.large - shorter) / (self.large - self.small).max(1e-3)).clamp(0., 1.)
+ }
}
mod serde_poly {
@@ -78,7 +241,7 @@ mod serde_poly {
let values = Vec::<f32>::deserialize(d)?;
values
.try_into()
- .map_err(|_| serde::de::Error::custom("poly needs 39 coefficients"))
+ .map_err(|_| serde::de::Error::custom("poly needs 3 x POLY_TERMS coefficients"))
}
}
@@ -99,6 +262,8 @@ pub struct PaneStyle {
pub glow: f32,
pub glow_width: f32,
pub hairline: [f32; 4],
+ /// Tint on the finished colour; [`TintMatrix::NONE`] when untinted.
+ pub tint: TintMatrix,
}
impl PaneStyle {
@@ -118,17 +283,29 @@ impl PaneStyle {
impl GlassMaterial {
/// Parameters the optimiser searches; the colour transform is solved.
- pub const SHAPE_FIELDS: usize = 16;
+ pub const SHAPE_FIELDS: usize = 19;
+
+ /// The colour transform a pane of this shorter side uses.
+ pub fn poly_for(&self, shorter: f32) -> [f32; 3 * POLY_TERMS] {
+ match &self.adapt {
+ Some(adapt) => {
+ let weight = adapt.weight(shorter);
+ std::array::from_fn(|i| self.poly[i] + (adapt.poly[i] - self.poly[i]) * weight)
+ }
+ None => self.poly,
+ }
+ }
pub fn resolve(&self, width: f32, height: f32) -> PaneStyle {
let shorter = width.min(height).max(1.);
- let lens_rim = (self.rim_k * shorter).clamp(0.5, self.rim_max.max(0.5));
+ let lens_rim = (self.rim_base + self.rim_k * shorter).clamp(0.5, self.rim_max.max(0.5));
+ let bend = (self.bend_base + self.bend_k * shorter).clamp(0., self.bend_max.max(0.));
PaneStyle {
blur: (self.blur_k * shorter).clamp(0., self.blur_max.max(0.)),
lens_rim,
lens_curve: self.lens_curve,
- rim_bend: self.bend * lens_rim,
- poly: self.poly,
+ rim_bend: -bend,
+ poly: self.poly_for(shorter),
opacity: self.opacity,
line: self.line,
line_lit: self.line_lit,
@@ -137,16 +314,27 @@ impl GlassMaterial {
glow: self.glow,
glow_width: self.glow_width,
hairline: self.hairline,
+ tint: TintMatrix::NONE,
}
}
+ /// The tint `color` (sRGB 0-1) at `alpha` on this material, or no tint
+ /// for a material without a measured tint law.
+ pub fn tint_matrix(&self, color: [f32; 3], alpha: f32) -> TintMatrix {
+ self.tint
+ .map_or(TintMatrix::NONE, |law| law.matrix(color, alpha))
+ }
+
pub fn shape_vec(&self) -> [f32; Self::SHAPE_FIELDS] {
[
self.blur_k,
self.blur_max,
+ self.rim_base,
self.rim_k,
self.rim_max,
- self.bend,
+ self.bend_base,
+ self.bend_k,
+ self.bend_max,
self.lens_curve,
self.line,
self.line_lit,
@@ -165,17 +353,20 @@ impl GlassMaterial {
Self {
blur_k: values[0].max(0.),
blur_max: values[1].max(0.),
- rim_k: values[2].max(0.),
- rim_max: values[3].max(0.5),
- bend: values[4],
- lens_curve: values[5].clamp(0.2, 6.),
- line: values[6],
- line_lit: values[7],
- line_width: values[8].max(0.3),
- light_angle: values[9],
- glow: values[10],
- glow_width: values[11].max(0.5),
- hairline: [values[12], values[13], values[14], values[15]],
+ rim_base: values[2].max(0.),
+ rim_k: values[3].max(0.),
+ rim_max: values[4].max(0.5),
+ bend_base: values[5],
+ bend_k: values[6],
+ bend_max: values[7].max(0.),
+ lens_curve: values[8].clamp(0.2, 6.),
+ line: values[9],
+ line_lit: values[10],
+ line_width: values[11].max(0.3),
+ light_angle: values[12],
+ glow: values[13],
+ glow_width: values[14].max(0.5),
+ hairline: [values[15], values[16], values[17], values[18]],
..*self
}
}
@@ -217,8 +408,11 @@ pub fn sample(style: &PaneStyle, shape: &Shape, blurred: &Rgba, px: f32, py: f32
};
}
let edge = (-d).max(0.);
- let rim = 1. - (edge / style.lens_rim).clamp(0., 1.).powf(style.lens_curve);
- let value = blurred.sample(px + nx * style.rim_bend * rim, py + ny * style.rim_bend * rim);
+ let rim = (-(edge / style.lens_rim).powf(style.lens_curve)).exp();
+ let value = blurred.sample(
+ px + nx * style.rim_bend * rim,
+ py + ny * style.rim_bend * rim,
+ );
let facing = nx * style.light[0] + ny * style.light[1];
GlassSample {
source: [value[0] / 255., value[1] / 255., value[2] / 255.],
@@ -233,19 +427,22 @@ pub fn sample(style: &PaneStyle, shape: &Shape, blurred: &Rgba, px: f32, py: f32
/// The backdrop under a glass pixel once the hairline is drawn on it (0-1).
pub fn under_with_hairline(sample: &GlassSample, under: [f32; 3]) -> [f32; 3] {
std::array::from_fn(|i| {
- let line = under[i].min(sample.hairline[0] * under[i] + sample.hairline[1]).clamp(0., 1.);
+ let line = under[i]
+ .min(sample.hairline[0] * under[i] + sample.hairline[1])
+ .clamp(0., 1.);
under[i] + (line - under[i]) * sample.ring
})
}
-/// Apply the colour transform and lighting: 0-1 sRGB out, unclamped.
+/// Apply the colour transform, lighting and tint: 0-1 sRGB out, unclamped.
pub fn finish(style: &PaneStyle, sample: &GlassSample) -> [f32; 3] {
let features = poly_features(sample.source);
- std::array::from_fn(|channel| {
+ let untinted: [f32; 3] = std::array::from_fn(|channel| {
let coefficients = &style.poly[channel * POLY_TERMS..(channel + 1) * POLY_TERMS];
let value: f32 = coefficients.iter().zip(features).map(|(c, f)| c * f).sum();
- value * sample.scale + sample.glow
- })
+ (value * sample.scale + sample.glow).clamp(0., 1.)
+ });
+ style.tint.apply(untinted)
}
/// Composite one pane over `out`, sampling `blurred` (the backdrop blurred
@@ -262,9 +459,15 @@ pub fn composite(style: &PaneStyle, shape: &Shape, blurred: &Rgba, out: &mut Rgb
continue;
}
let under = out.get(x, y);
- let under = under_with_hairline(&glass, [under[0] / 255., under[1] / 255., under[2] / 255.]);
- let color = if glass.coverage > 0. { finish(style, &glass) } else { under };
- let mix = |i: usize| (under[i] + (color[i].clamp(0., 1.) - under[i]) * glass.coverage) * 255.;
+ let under =
+ under_with_hairline(&glass, [under[0] / 255., under[1] / 255., under[2] / 255.]);
+ let color = if glass.coverage > 0. {
+ finish(style, &glass)
+ } else {
+ under
+ };
+ let mix =
+ |i: usize| (under[i] + (color[i].clamp(0., 1.) - under[i]) * glass.coverage) * 255.;
out.set(x, y, [mix(0), mix(1), mix(2), 255.]);
}
}
diff --git a/apps/desktop-gpui/glass/tests/presets.rs b/apps/desktop-gpui/glass/tests/presets.rs
index ac2e1d93e..c761851ad 100644
--- a/apps/desktop-gpui/glass/tests/presets.rs
+++ b/apps/desktop-gpui/glass/tests/presets.rs
@@ -47,7 +47,12 @@ fn presets_match_apple_over_flat_backdrops() {
#[test]
fn every_preset_is_complete() {
let all = presets();
- let names: Vec<&str> = all.as_object().unwrap().keys().map(String::as_str).collect();
+ let names: Vec<&str> = all
+ .as_object()
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect();
assert_eq!(
names,
["clear-dark", "clear-light", "regular-dark", "regular-light"]
@@ -85,7 +90,10 @@ fn the_rounded_rect_distance_field_is_signed_and_clamps_its_radius() {
assert!((shape.sdf(50., 20.) + 20.).abs() < 1e-4);
assert!((shape.sdf(50., -5.) - 5.).abs() < 1e-4);
assert!((shape.sdf(0., 20.)).abs() < 1e-4);
- assert!(shape.sdf(1., 1.) > 0., "a corner beyond the clamped radius is outside");
+ assert!(
+ shape.sdf(1., 1.) > 0.,
+ "a corner beyond the clamped radius is outside"
+ );
let (nx, ny) = shape.normal(50., 1.);
assert!(nx.abs() < 1e-3 && (ny + 1.).abs() < 1e-3);
}
@@ -112,3 +120,100 @@ fn glass_leaves_pixels_beyond_its_hairline_alone() {
assert_eq!(out.get(x, y), backdrop.get(x, y), "({x}, {y})");
}
}
+
+fn centre_of(
+ material: &GlassMaterial,
+ gray: f32,
+ shape: Shape,
+ tint: Option<([f32; 3], f32)>,
+) -> [f32; 3] {
+ let backdrop = Rgba::solid(960, 600, [gray, gray, gray, 255.]);
+ let mut style = material.resolve(shape.width, shape.height);
+ if let Some((color, alpha)) = tint {
+ style.tint = material.tint_matrix(color, alpha);
+ }
+ let mut out = backdrop.clone();
+ model::composite(&style, &shape, &backdrop.blurred(style.blur), &mut out);
+ let pixel = out.get(
+ (shape.x + shape.width / 2.) as usize,
+ (shape.y + shape.height / 2.) as usize,
+ );
+ [pixel[0], pixel[1], pixel[2]]
+}
+
+fn pane(side: f32) -> Shape {
+ Shape {
+ x: 100.,
+ y: 100.,
+ width: 400.,
+ height: side,
+ radius: side / 2.,
+ }
+}
+
+/// Regular dark glass lifts small panes over bright content: over white,
+/// Apple's reads 180 up to 64 pt tall, 154 at 80 pt, 127 at 96 pt and 114
+/// from 128 pt (`sweep`, macOS 27.0.1).
+#[test]
+fn regular_dark_adapts_to_pane_size() {
+ let material = material("regular-dark");
+ for (side, apple) in [
+ (44., 180.),
+ (64., 180.),
+ (80., 154.),
+ (96., 127.),
+ (128., 114.),
+ (240., 114.),
+ ] {
+ let got = centre_of(&material, 255., pane(side), None)[0];
+ eprintln!("regular-dark {side} pt over white -> {got:.1} (apple {apple})");
+ assert!(
+ (got - apple).abs() <= 3.,
+ "{side} pt: {got} vs Apple's {apple}"
+ );
+ }
+}
+
+/// Apple's tints over mid grey, read off the `sweep` captures: Regular
+/// ignores the hue and shifts grey, Clear blends the colour in.
+#[test]
+fn tints_match_apple_over_mid_grey() {
+ let blue = ([0., 0.533, 1.], 0.6);
+ let red = ([1., 0.22, 0.235], 0.6);
+ for (name, tint, apple) in [
+ ("regular-light", blue, [172., 172., 172.]),
+ ("regular-dark", blue, [126., 125., 126.]),
+ ("regular-light", red, [172., 172., 172.]),
+ ("clear-light", blue, [63., 130., 193.]),
+ ("clear-dark", blue, [46., 107., 166.]),
+ ] {
+ let got = centre_of(&material(name), 128., pane(240.), Some(tint));
+ eprintln!("{name} {tint:?} over 128 -> {got:?} (apple {apple:?})");
+ for c in 0..3 {
+ assert!(
+ (got[c] - apple[c]).abs() <= 3.,
+ "{name} channel {c}: {got:?} vs Apple's {apple:?}"
+ );
+ }
+ }
+}
+
+/// Apple's refraction at the edge grows with the pane up to a cap: about
+/// 0.52 px per point for Clear up to 45 px, 11 + 0.08 px per point for
+/// Regular up to 26 px (`sweep lens`).
+#[test]
+fn lens_amplitude_follows_apple() {
+ for (name, side, apple) in [
+ ("clear-light", 20., 10.9),
+ ("clear-light", 44., 23.5),
+ ("clear-light", 270., 44.1),
+ ("regular-light", 44., 14.3),
+ ("regular-light", 270., 25.6),
+ ] {
+ let got = -material(name).resolve(400., side).rim_bend;
+ assert!(
+ (got - apple).abs() <= 2.,
+ "{name} {side} pt: {got} vs Apple's {apple}"
+ );
+ }
+}
diff --git a/apps/desktop-gpui/patches/zed-glass.patch b/apps/desktop-gpui/patches/zed-glass.patch
index 033ae8ce5..340be7e9d 100644
--- a/apps/desktop-gpui/patches/zed-glass.patch
+++ b/apps/desktop-gpui/patches/zed-glass.patch
@@ -1,5 +1,5 @@
diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs
-index 6cc3562..c49648d 100644
+index 6cc3562..4c1f558 100644
--- a/crates/gpui/src/scene.rs
+++ b/crates/gpui/src/scene.rs
@@ -52,7 +52,7 @@ pub struct Scene {
@@ -22,7 +22,7 @@ index 6cc3562..c49648d 100644
#[derive(Debug, Copy, Clone)]
#[repr(C)]
#[expect(missing_docs)]
-@@ -624,6 +624,78 @@ pub struct BackdropBlur {
+@@ -624,6 +624,87 @@ pub struct BackdropBlur {
pub bounds: Bounds<ScaledPixels>,
pub content_mask: ContentMask<ScaledPixels>,
pub corner_radii: Corners<ScaledPixels>,
@@ -52,7 +52,7 @@ index 6cc3562..c49648d 100644
+ pub lens_rim: f32,
+ pub lens_curve: f32,
+ pub rim_bend: f32,
-+ pub poly: [f32; 39],
++ pub poly: [f32; 60],
+ pub opacity: f32,
+ pub line: f32,
+ pub line_lit: f32,
@@ -62,8 +62,14 @@ index 6cc3562..c49648d 100644
+ pub glow: f32,
+ pub glow_width: f32,
+ pub hairline: [f32; 4],
-+ /// Keeps the struct a multiple of 8 bytes, which WGSL's storage layout
-+ /// requires of `BackdropBlur`.
++ /// Tint, a colour matrix on the finished glass colour: `color *
++ /// tint_scale + luma(color) * tint_luma + tint_offset` per channel, with
++ /// Rec. 709 luma of the gamma-encoded colour. Untinted glass has a scale
++ /// of 1 and nothing else. The struct stays a multiple of 8 bytes, which
++ /// WGSL's storage layout requires of `BackdropBlur`.
++ pub tint_scale: [f32; 3],
++ pub tint_luma: [f32; 3],
++ pub tint_offset: [f32; 3],
+ pub pad: f32,
+}
+
@@ -74,7 +80,7 @@ index 6cc3562..c49648d 100644
+ lens_rim: 0.,
+ lens_curve: 0.,
+ rim_bend: 0.,
-+ poly: [0.; 39],
++ poly: [0.; 60],
+ opacity: 0.,
+ line: 0.,
+ line_lit: 0.,
@@ -84,6 +90,9 @@ index 6cc3562..c49648d 100644
+ glow: 0.,
+ glow_width: 0.,
+ hairline: [0.; 4],
++ tint_scale: [1.; 3],
++ tint_luma: [0.; 3],
++ tint_offset: [0.; 3],
+ pad: 0.,
+ }
+ }
@@ -173,7 +182,7 @@ index 70e9a0b..79415df 100644
"Underline".into(),
"UnderlineInputIndex".into(),
diff --git a/crates/gpui_macos/src/metal_renderer.rs b/crates/gpui_macos/src/metal_renderer.rs
-index 4be15aa..56248f3 100644
+index 4be15aa..a4f34d0 100644
--- a/crates/gpui_macos/src/metal_renderer.rs
+++ b/crates/gpui_macos/src/metal_renderer.rs
@@ -979,7 +979,7 @@ impl MetalRenderer {
@@ -238,7 +247,7 @@ index 4be15aa..56248f3 100644
});
scene.pop_layer();
}
-@@ -2741,6 +2750,215 @@ mod backdrop_blur_tests {
+@@ -2741,6 +2750,249 @@ mod backdrop_blur_tests {
);
}
@@ -246,22 +255,29 @@ index 4be15aa..56248f3 100644
+ let mut x = 0.;
+ let mut dark = true;
+ while x < VIEW_W as f32 {
-+ push_quad(scene, bounds(x, 0., 8., VIEW_H as f32), if dark { 0.05 } else { 0.95 });
++ push_quad(
++ scene,
++ bounds(x, 0., 8., VIEW_H as f32),
++ if dark { 0.05 } else { 0.95 },
++ );
+ x += 8.;
+ dark = !dark;
+ }
+ }
+
+ fn test_glass() -> GlassStyle {
-+ let mut poly = [0.; 39];
-+ poly[..13].copy_from_slice(&[
-+ 0.6, 0.15, 0.05, -0.2, 0.1, 0.0, 0.05, 0.0, 0.02, 0.1, 0.0, -0.02, 0.22,
++ let mut poly = [0.; 60];
++ poly[..20].copy_from_slice(&[
++ 0.6, 0.15, 0.05, -0.2, 0.1, 0.0, 0.05, 0.0, 0.02, 0.1, 0.0, -0.02, 0.04, -0.03,
++ 0.0, 0.02, 0.0, 0.0, 0.05, 0.22,
+ ]);
-+ poly[13..26].copy_from_slice(&[
-+ 0.05, 0.5, 0.1, 0.0, -0.15, 0.05, 0.0, 0.04, 0.0, 0.0, 0.08, 0.0, 0.2,
++ poly[20..40].copy_from_slice(&[
++ 0.05, 0.5, 0.1, 0.0, -0.15, 0.05, 0.0, 0.04, 0.0, 0.0, 0.08, 0.0, 0.0, 0.03, -0.04,
++ 0.0, 0.02, 0.0, -0.03, 0.2,
+ ]);
-+ poly[26..].copy_from_slice(&[
-+ 0.12, 0.05, 0.55, 0.0, 0.0, -0.1, 0.02, 0.0, 0.03, -0.03, 0.0, 0.06, 0.18,
++ poly[40..].copy_from_slice(&[
++ 0.12, 0.05, 0.55, 0.0, 0.0, -0.1, 0.02, 0.0, 0.03, -0.03, 0.0, 0.06, 0.0, 0.0,
++ 0.03, 0.0, -0.05, 0.04, 0.02, 0.18,
+ ]);
+ GlassStyle {
+ enabled: 1,
@@ -278,6 +294,9 @@ index 4be15aa..56248f3 100644
+ glow: 0.04,
+ glow_width: 6.,
+ hairline: [0.86, -0.12, 0.92, -0.08],
++ tint_scale: [0.4, 0.4, 0.4],
++ tint_luma: [0.05, 0.12, 0.25],
++ tint_offset: [0.02, 0.15, 0.3],
+ pad: 0.,
+ }
+ }
@@ -388,7 +407,8 @@ index 4be15aa..56248f3 100644
+
+ let mut errors = Vec::new();
+ for y in (pane.origin.y.0 as i32 - 2)..(pane.origin.y.0 + pane.size.height.0) as i32 + 2 {
-+ for x in (pane.origin.x.0 as i32 - 2)..(pane.origin.x.0 + pane.size.width.0) as i32 + 2 {
++ for x in (pane.origin.x.0 as i32 - 2)..(pane.origin.x.0 + pane.size.width.0) as i32 + 2
++ {
+ let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
+ let d = sdf(px, py);
+ let coverage = (0.5 - d).clamp(0., 1.);
@@ -412,8 +432,11 @@ index 4be15aa..56248f3 100644
+ under
+ } else {
+ let edge = (-d).max(0.);
-+ let rim = 1. - (edge / glass.lens_rim).clamp(0., 1.).powf(glass.lens_curve);
-+ let s = sample(px + nx * glass.rim_bend * rim, py + ny * glass.rim_bend * rim);
++ let rim = (-(edge / glass.lens_rim).powf(glass.lens_curve)).exp();
++ let s = sample(
++ px + nx * glass.rim_bend * rim,
++ py + ny * glass.rim_bend * rim,
++ );
+ let c = [s[0] / 255., s[1] / 255., s[2] / 255.];
+ let features = [
+ c[0],
@@ -428,14 +451,31 @@ index 4be15aa..56248f3 100644
+ c[0] * c[0] * c[0],
+ c[1] * c[1] * c[1],
+ c[2] * c[2] * c[2],
++ c[0] * c[0] * c[1],
++ c[0] * c[0] * c[2],
++ c[1] * c[1] * c[0],
++ c[1] * c[1] * c[2],
++ c[2] * c[2] * c[0],
++ c[2] * c[2] * c[1],
++ c[0] * c[1] * c[2],
+ 1.,
+ ];
+ let facing = nx * glass.light_x + ny * glass.light_y;
-+ let line = (-edge / glass.line_width).exp() * (glass.line + glass.line_lit * facing);
++ let line =
++ (-edge / glass.line_width).exp() * (glass.line + glass.line_lit * facing);
+ let glow = (-edge / glass.glow_width).exp() * glass.glow;
++ let shaded: [f32; 3] = std::array::from_fn(|i| {
++ let value: f32 =
++ (0..20).map(|t| glass.poly[i * 20 + t] * features[t]).sum();
++ (value * (1. + line) + glow).clamp(0., 1.)
++ });
++ let luma = shaded[0] * 0.2126 + shaded[1] * 0.7152 + shaded[2] * 0.0722;
+ std::array::from_fn(|i| {
-+ let value: f32 = (0..13).map(|t| glass.poly[i * 13 + t] * features[t]).sum();
-+ let value = (value * (1. + line) + glow).clamp(0., 1.) * 255.;
++ let value = (shaded[i] * glass.tint_scale[i]
++ + luma * glass.tint_luma[i]
++ + glass.tint_offset[i])
++ .clamp(0., 1.)
++ * 255.;
+ under[i] + (value - under[i]) * coverage
+ })
+ };
@@ -448,14 +488,17 @@ index 4be15aa..56248f3 100644
+ errors.sort_by(f32::total_cmp);
+ let mean = errors.iter().sum::<f32>() / errors.len() as f32;
+ let p99 = errors[errors.len() * 99 / 100];
-+ assert!(mean < 1.5 && p99 < 8., "glass vs CPU model: mean {mean:.2}, p99 {p99:.2}");
++ assert!(
++ mean < 1.5 && p99 < 8.,
++ "glass vs CPU model: mean {mean:.2}, p99 {p99:.2}"
++ );
+ }
+
#[test]
fn two_blurs_of_different_sizes_in_one_frame() {
if metal::Device::system_default().is_none() {
diff --git a/crates/gpui_macos/src/shaders.metal b/crates/gpui_macos/src/shaders.metal
-index e087c0d..de1333f 100644
+index e087c0d..1a5848c 100644
--- a/crates/gpui_macos/src/shaders.metal
+++ b/crates/gpui_macos/src/shaders.metal
@@ -1354,9 +1354,17 @@ vertex BackdropBlurVertexOutput backdrop_blur_vertex(
@@ -478,18 +521,21 @@ index e087c0d..de1333f 100644
blur.content_mask.bounds);
return BackdropBlurVertexOutput{
device_position,
-@@ -1364,26 +1372,78 @@ vertex BackdropBlurVertexOutput backdrop_blur_vertex(
+@@ -1364,26 +1372,88 @@ vertex BackdropBlurVertexOutput backdrop_blur_vertex(
{clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
}
+float3 glass_shade(GlassStyle glass, float3 c, float edge, float2 normal) {
-+ float features[13] = {c.r, c.g, c.b, c.r * c.r, c.g * c.g, c.b * c.b,
++ // The full cubic in r, g and b; `cap_glass::model::poly_features`.
++ float features[20] = {c.r, c.g, c.b, c.r * c.r, c.g * c.g, c.b * c.b,
+ c.r * c.g, c.g * c.b, c.r * c.b, c.r * c.r * c.r,
-+ c.g * c.g * c.g, c.b * c.b * c.b, 1.};
++ c.g * c.g * c.g, c.b * c.b * c.b, c.r * c.r * c.g,
++ c.r * c.r * c.b, c.g * c.g * c.r, c.g * c.g * c.b,
++ c.b * c.b * c.r, c.b * c.b * c.g, c.r * c.g * c.b, 1.};
+ float3 color = float3(0.);
-+ for (int term = 0; term < 13; term++) {
++ for (int term = 0; term < 20; term++) {
+ color += features[term] *
-+ float3(glass.poly[term], glass.poly[13 + term], glass.poly[26 + term]);
++ float3(glass.poly[term], glass.poly[20 + term], glass.poly[40 + term]);
+ }
+ float facing = dot(normal, float2(glass.light_x, glass.light_y));
+ float line = exp(-edge / glass.line_width) * (glass.line + glass.line_lit * facing);
@@ -559,20 +605,27 @@ index e087c0d..de1333f 100644
+ return under;
+ }
+ float edge = max(-distance, 0.);
-+ float rim = 1. - pow(saturate(edge / blur.glass.lens_rim), blur.glass.lens_curve);
++ float rim = exp(-pow(edge / blur.glass.lens_rim, blur.glass.lens_curve));
+ float2 sample_at = position + normal * blur.glass.rim_bend * rim;
+ float4 backdrop = source_texture.sample(
+ source_sampler, (sample_at - source_rect.xy) / source_rect.zw);
+ float3 straight = backdrop.a > 0. ? backdrop.rgb / backdrop.a : float3(0.);
+ float alpha = mix(backdrop.a, 1., blur.glass.opacity);
+ float3 glass = saturate(glass_shade(blur.glass, straight, edge, normal));
++ float luma = dot(glass, float3(0.2126, 0.7152, 0.0722));
++ glass = saturate(glass * float3(blur.glass.tint_scale[0], blur.glass.tint_scale[1],
++ blur.glass.tint_scale[2]) +
++ luma * float3(blur.glass.tint_luma[0], blur.glass.tint_luma[1],
++ blur.glass.tint_luma[2]) +
++ float3(blur.glass.tint_offset[0], blur.glass.tint_offset[1],
++ blur.glass.tint_offset[2]));
+ return mix(under, float4(glass * alpha, alpha), coverage);
}
diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl
-index 011be71..5c7194d 100644
+index 011be71..2b82b2b 100644
--- a/crates/gpui_wgpu/src/shaders.wgsl
+++ b/crates/gpui_wgpu/src/shaders.wgsl
-@@ -1399,3 +1399,195 @@ fn fs_surface(input: SurfaceVarying) -> @location(0) vec4<f32> {
+@@ -1399,3 +1399,204 @@ fn fs_surface(input: SurfaceVarying) -> @location(0) vec4<f32> {
return ycbcr_to_RGB * y_cb_cr;
}
@@ -584,7 +637,7 @@ index 011be71..5c7194d 100644
+ lens_rim: f32,
+ lens_curve: f32,
+ rim_bend: f32,
-+ poly: array<f32, 39>,
++ poly: array<f32, 60>,
+ opacity: f32,
+ line_strength: f32,
+ line_lit: f32,
@@ -594,6 +647,9 @@ index 011be71..5c7194d 100644
+ glow: f32,
+ glow_width: f32,
+ hairline: array<f32, 4>,
++ tint_scale: array<f32, 3>,
++ tint_luma: array<f32, 3>,
++ tint_offset: array<f32, 3>,
+ pad: f32,
+}
+
@@ -748,23 +804,29 @@ index 011be71..5c7194d 100644
+ if (coverage <= 0.0) {
+ return under;
+ }
-+ let rim = 1.0 - pow(saturate(edge / glass.lens_rim), glass.lens_curve);
++ let rim = exp(-pow(edge / glass.lens_rim, glass.lens_curve));
+ let sample_at = position + normal * glass.rim_bend * rim;
+ let backdrop = textureSampleLevel(t_backdrop, s_backdrop, backdrop_blurred_uv(sample_at), 0.0);
+ var color = select(vec3<f32>(0.0), backdrop.rgb / backdrop.a, backdrop.a > 0.0);
+ let alpha = mix(backdrop.a, 1.0, glass.opacity);
+
+ let c = color;
-+ let features = array<f32, 13>(c.r, c.g, c.b, c.r * c.r, c.g * c.g, c.b * c.b,
-+ c.r * c.g, c.g * c.b, c.r * c.b, c.r * c.r * c.r, c.g * c.g * c.g, c.b * c.b * c.b, 1.0);
++ let features = array<f32, 20>(c.r, c.g, c.b, c.r * c.r, c.g * c.g, c.b * c.b,
++ c.r * c.g, c.g * c.b, c.r * c.b, c.r * c.r * c.r, c.g * c.g * c.g, c.b * c.b * c.b,
++ c.r * c.r * c.g, c.r * c.r * c.b, c.g * c.g * c.r, c.g * c.g * c.b,
++ c.b * c.b * c.r, c.b * c.b * c.g, c.r * c.g * c.b, 1.0);
+ color = vec3<f32>(0.0);
-+ for (var term = 0; term < 13; term++) {
-+ color += features[term] * vec3<f32>(glass.poly[term], glass.poly[13 + term], glass.poly[26 + term]);
++ for (var term = 0; term < 20; term++) {
++ color += features[term] * vec3<f32>(glass.poly[term], glass.poly[20 + term], glass.poly[40 + term]);
+ }
+ let facing = dot(normal, vec2<f32>(glass.light_x, glass.light_y));
+ let line_term = exp(-edge / glass.line_width) * (glass.line_strength + glass.line_lit * facing);
+ let glow = exp(-edge / glass.glow_width) * glass.glow;
+ color = saturate(color * (1.0 + line_term) + vec3<f32>(glow));
++ let luma = dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));
++ color = saturate(color * vec3<f32>(glass.tint_scale[0], glass.tint_scale[1], glass.tint_scale[2])
++ + luma * vec3<f32>(glass.tint_luma[0], glass.tint_luma[1], glass.tint_luma[2])
++ + vec3<f32>(glass.tint_offset[0], glass.tint_offset[1], glass.tint_offset[2]));
+
+ return mix(under, vec4<f32>(color * alpha, alpha), coverage);
+}
@@ -1879,10 +1941,10 @@ index e4b605b..89f3cbb 100644
}
}
diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl
-index 78b1ada..5ae5ab5 100644
+index 78b1ada..fa802f7 100644
--- a/crates/gpui_windows/src/shaders.hlsl
+++ b/crates/gpui_windows/src/shaders.hlsl
-@@ -1289,3 +1289,200 @@ float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Targe
+@@ -1289,3 +1289,211 @@ float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Targe
color.a *= sprite.opacity * saturate(0.5 - distance) * edge_fade_alpha(input.position.xy, sprite.fade);
return color;
}
@@ -1900,7 +1962,7 @@ index 78b1ada..5ae5ab5 100644
+ float lens_rim;
+ float lens_curve;
+ float rim_bend;
-+ float poly[39];
++ float poly[60];
+ float opacity;
+ float line_strength;
+ float line_lit;
@@ -1910,6 +1972,9 @@ index 78b1ada..5ae5ab5 100644
+ float glow;
+ float glow_width;
+ float hairline[4];
++ float tint_scale[3];
++ float tint_luma[3];
++ float tint_offset[3];
+ float pad;
+};
+
@@ -2061,25 +2126,33 @@ index 78b1ada..5ae5ab5 100644
+ if (coverage <= 0.) {
+ return under;
+ }
-+ float rim = 1. - pow(saturate(edge / glass.lens_rim), glass.lens_curve);
++ float rim = exp(-pow(edge / glass.lens_rim, glass.lens_curve));
+ float2 sample_at = position + normal * glass.rim_bend * rim;
+ float4 backdrop = t_backdrop.SampleLevel(s_backdrop, backdrop_blurred_uv(sample_at), 0);
+ float3 color = backdrop.a > 0. ? backdrop.rgb / backdrop.a : float3(0., 0., 0.);
+ float alpha = lerp(backdrop.a, 1., glass.opacity);
+
-+ float features[13] = {color.r, color.g, color.b, color.r * color.r, color.g * color.g,
++ float features[20] = {color.r, color.g, color.b, color.r * color.r, color.g * color.g,
+ color.b * color.b, color.r * color.g, color.g * color.b,
+ color.r * color.b, color.r * color.r * color.r,
-+ color.g * color.g * color.g, color.b * color.b * color.b, 1.};
++ color.g * color.g * color.g, color.b * color.b * color.b,
++ color.r * color.r * color.g, color.r * color.r * color.b,
++ color.g * color.g * color.r, color.g * color.g * color.b,
++ color.b * color.b * color.r, color.b * color.b * color.g,
++ color.r * color.g * color.b, 1.};
+ color = float3(0., 0., 0.);
+ [unroll]
-+ for (int term = 0; term < 13; term++) {
-+ color += features[term] * float3(glass.poly[term], glass.poly[13 + term], glass.poly[26 + term]);
++ for (int term = 0; term < 20; term++) {
++ color += features[term] * float3(glass.poly[term], glass.poly[20 + term], glass.poly[40 + term]);
+ }
+ float facing = dot(normal, float2(glass.light_x, glass.light_y));
+ float line_term = exp(-edge / glass.line_width) * (glass.line_strength + glass.line_lit * facing);
+ float glow = exp(-edge / glass.glow_width) * glass.glow;
+ color = saturate(color * (1. + line_term) + glow);
++ float luma = dot(color, float3(0.2126, 0.7152, 0.0722));
++ color = saturate(color * float3(glass.tint_scale[0], glass.tint_scale[1], glass.tint_scale[2])
++ + luma * float3(glass.tint_luma[0], glass.tint_luma[1], glass.tint_luma[2])
++ + float3(glass.tint_offset[0], glass.tint_offset[1], glass.tint_offset[2]));
+
+ return lerp(under, float4(color * alpha, alpha), coverage);
+}
diff --git a/apps/desktop-gpui/src/glass_probe.rs b/apps/desktop-gpui/src/glass_probe.rs
index aa8ea888c..367895885 100644
--- a/apps/desktop-gpui/src/glass_probe.rs
+++ b/apps/desktop-gpui/src/glass_probe.rs
@@ -21,10 +21,27 @@ const PRESETS: [(&str, GlassKind, bool); 4] = [
/// with glass panes in each preset, capture the window, and score it against
/// the CPU model of the same material. Writes the captures, the model's
/// renders and `report.json`, whose `passed` is the CI verdict.
+///
+/// With `CAP_GLASS_PROBE_REFERENCE=<dir>` it replays a corpus from
+/// `scripts/glass-reference` instead: every case's backdrop, panes and tint,
+/// scored against Apple's capture of the same case, so captures from each
+/// OS line up with Apple's and with each other. `CAP_GLASS_PROBE_CASES`
+/// limits it to cases whose names start with one of its comma-separated
+/// prefixes.
pub fn run(cx: &mut App) {
let Some(output) = std::env::var_os("CAP_GLASS_PROBE_OUTPUT").map(PathBuf::from) else {
return;
};
+ let reference = match std::env::var_os("CAP_GLASS_PROBE_REFERENCE").map(PathBuf::from) {
+ Some(dir) => match Reference::load(&dir) {
+ Ok(reference) => Some(Arc::new(reference)),
+ Err(error) => {
+ tracing::error!(%error, "glass probe: cannot read the reference corpus");
+ return;
+ }
+ },
+ None => None,
+ };
if let Err(error) = std::fs::create_dir_all(&output) {
tracing::error!(%error, "glass probe: cannot create its output directory");
return;
@@ -55,7 +72,10 @@ pub fn run(cx: &mut App) {
}
};
cx.spawn(async move |cx| {
- let report = probe(handle, &output, cx).await;
+ let report = match reference {
+ Some(reference) => probe_reference(handle, &reference, &output, cx).await,
+ None => probe(handle, &output, cx).await,
+ };
if let Err(error) = std::fs::write(output.join("report.json"), report.to_string()) {
tracing::error!(%error, "glass probe: could not write its report");
}
@@ -64,24 +84,39 @@ pub fn run(cx: &mut App) {
.detach();
}
-#[derive(Default)]
struct ProbeView {
scene: Option<Arc<RenderImage>>,
preset: Option<(GlassKind, bool)>,
+ shapes: Vec<Shape>,
+ tint: Option<glass::Tint>,
+}
+
+impl Default for ProbeView {
+ fn default() -> Self {
+ Self {
+ scene: None,
+ preset: None,
+ shapes: scenes::SHAPES.to_vec(),
+ tint: None,
+ }
+ }
}
impl Render for ProbeView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- let mut root = div()
- .size_full()
- .relative()
- .bg(gpui::white())
- .children(self.scene.clone().map(|scene| img(scene).absolute().size_full()));
+ let mut root = div().size_full().relative().bg(gpui::white()).children(
+ self.scene
+ .clone()
+ .map(|scene| img(scene).absolute().size_full()),
+ );
if let Some((kind, dark)) = self.preset {
- for shape in scenes::SHAPES {
+ for shape in &self.shapes {
+ let pane = match self.tint {
+ Some(tint) => glass::pane_tinted(kind, dark, shape.radius, tint),
+ None => glass::pane(kind, dark, shape.radius),
+ };
root = root.child(
- glass::pane(kind, dark, shape.radius)
- .absolute()
+ pane.absolute()
.left(px(shape.x))
.top(px(shape.y))
.w(px(shape.width))
@@ -156,7 +191,11 @@ async fn probe(
let captured = Rgba {
width: captured.width() as usize,
height: captured.height() as usize,
- pixels: captured.as_raw().iter().map(|value| *value as f32).collect(),
+ pixels: captured
+ .as_raw()
+ .iter()
+ .map(|value| *value as f32)
+ .collect(),
};
let expected = expected_render(&scene, glass::material(kind, dark), scale);
let mask = glass_mask(scale, captured.width, captured.height);
@@ -180,6 +219,210 @@ async fn probe(
serde_json::json!({ "passed": passed, "scale": scale, "cases": cases })
}
+/// A corpus written by `scripts/glass-reference` (`reference` or `sweep`).
+struct Reference {
+ dir: PathBuf,
+ shapes: Vec<Shape>,
+ cases: Vec<ReferenceCase>,
+ tints: std::collections::HashMap<String, [f32; 4]>,
+}
+
+#[derive(serde::Deserialize)]
+struct ReferenceManifest {
+ shapes: Vec<ReferenceShape>,
+ cases: Vec<ReferenceCase>,
+ #[serde(default)]
+ tints: std::collections::HashMap<String, [f32; 4]>,
+}
+
+#[derive(serde::Deserialize)]
+struct ReferenceShape {
+ rect: [f32; 4],
+ radius: f32,
+}
+
+#[derive(serde::Deserialize, Clone)]
+struct ReferenceCase {
+ name: String,
+ scene: String,
+ style: String,
+ appearance: String,
+ tint: String,
+ #[serde(default)]
+ pass: String,
+}
+
+impl Reference {
+ fn load(dir: &std::path::Path) -> anyhow::Result<Self> {
+ let manifest: ReferenceManifest =
+ serde_json::from_slice(&std::fs::read(dir.join("manifest.json"))?)?;
+ let prefixes: Vec<String> = std::env::var("CAP_GLASS_PROBE_CASES")
+ .map(|list| list.split(',').map(str::to_owned).collect())
+ .unwrap_or_default();
+ Ok(Self {
+ dir: dir.to_owned(),
+ shapes: manifest
+ .shapes
+ .iter()
+ .map(|shape| Shape {
+ x: shape.rect[0],
+ y: shape.rect[1],
+ width: shape.rect[2],
+ height: shape.rect[3],
+ radius: shape.radius,
+ })
+ .collect(),
+ cases: manifest
+ .cases
+ .into_iter()
+ // The sweep's falling pass repeats its rising one.
+ .filter(|case| case.pass != "down")
+ .filter(|case| {
+ prefixes.is_empty()
+ || prefixes.iter().any(|prefix| case.name.starts_with(prefix))
+ })
+ .collect(),
+ tints: manifest.tints,
+ })
+ }
+
+ /// `name` from the corpus at `width` x `height` device pixels.
+ fn image(&self, folder: &str, name: &str, width: u32, height: u32) -> Option<image::RgbaImage> {
+ let image = image::open(self.dir.join(folder).join(format!("{name}.png")))
+ .ok()?
+ .to_rgba8();
+ Some(if image.width() == width && image.height() == height {
+ image
+ } else {
+ image::imageops::resize(&image, width, height, image::imageops::FilterType::Triangle)
+ })
+ }
+}
+
+async fn probe_reference(
+ handle: WindowHandle<ProbeView>,
+ reference: &Reference,
+ output: &std::path::Path,
+ cx: &mut AsyncApp,
+) -> serde_json::Value {
+ sleep(cx, 1500).await;
+ let scale = handle
+ .update(cx, |_, window, _| window.scale_factor())
+ .unwrap_or(1.);
+ let Some(target) = handle
+ .update(cx, |_, window, _| window_target(window))
+ .ok()
+ .flatten()
+ else {
+ return serde_json::json!({ "passed": false, "error": "no window id to capture" });
+ };
+ let shapes = reference.shapes.clone();
+ handle
+ .update(cx, |view, _, _| view.shapes = shapes.clone())
+ .ok();
+ let (width, height) = (
+ (scenes::CANVAS.0 * scale).round() as u32,
+ (scenes::CANVAS.1 * scale).round() as u32,
+ );
+ let mask: Vec<bool> = (0..(width * height) as usize)
+ .map(|index| {
+ let x = (index % width as usize) as f32 + 0.5;
+ let y = (index / width as usize) as f32 + 0.5;
+ shapes
+ .iter()
+ .any(|shape| scaled(shape, scale).sdf(x, y) < 1.5)
+ })
+ .collect();
+ let mut scene_cache: std::collections::HashMap<String, Arc<RenderImage>> = Default::default();
+ let mut cases = Vec::new();
+ for case in &reference.cases {
+ let kind = match case.style.as_str() {
+ "clear" => GlassKind::Clear,
+ _ => GlassKind::Regular,
+ };
+ let dark = case.appearance == "dark";
+ let tint = reference
+ .tints
+ .get(&case.tint)
+ .map(|[r, g, b, a]| gpui::Rgba {
+ r: *r,
+ g: *g,
+ b: *b,
+ a: *a,
+ });
+ let scene = match scene_cache.get(&case.scene) {
+ Some(scene) => scene.clone(),
+ None => {
+ let Some(image) = reference.image("scenes", &case.scene, width, height) else {
+ cases.push(serde_json::json!({ "name": case.name, "error": "missing scene" }));
+ continue;
+ };
+ let scene = crate::library::rgba_to_render_image(image);
+ scene_cache.insert(case.scene.clone(), scene.clone());
+ scene
+ }
+ };
+ handle
+ .update(cx, |view, window, cx| {
+ view.scene = Some(scene);
+ view.preset = Some((kind, dark));
+ view.tint = tint;
+ cx.notify();
+ window.refresh();
+ })
+ .ok();
+ sleep(cx, 400).await;
+ let captured = {
+ let target = target.clone();
+ gpui_tokio::Tokio::spawn(cx, async move {
+ cap_recording::screenshot::capture_screenshot(target).await
+ })
+ .await
+ };
+ let captured = match captured {
+ Ok(Ok(image)) => crop_to(&image.to_rgba8(), width, height),
+ Ok(Err(error)) => {
+ cases.push(serde_json::json!({ "name": case.name, "error": format!("{error:#}") }));
+ continue;
+ }
+ Err(error) => {
+ cases.push(serde_json::json!({ "name": case.name, "error": error.to_string() }));
+ continue;
+ }
+ };
+ let _ = captured.save(output.join(format!("{}.png", case.name)));
+ let Some(apple) = reference.image("apple", &case.name, width, height) else {
+ cases.push(serde_json::json!({ "name": case.name, "error": "missing Apple capture" }));
+ continue;
+ };
+ let to_rgba = |image: &image::RgbaImage| Rgba {
+ width: image.width() as usize,
+ height: image.height() as usize,
+ pixels: image.as_raw().iter().map(|value| *value as f32).collect(),
+ };
+ let (ours, apple) = (to_rgba(&captured), to_rgba(&apple));
+ let ssim = metrics::ssim(&ours, &apple, &mask);
+ let (delta_e, delta_e95) = metrics::delta_e(&ours, &apple, &mask);
+ cases.push(serde_json::json!({
+ "name": case.name,
+ "ssim": ssim,
+ "deltaE": delta_e,
+ "deltaE95": delta_e95,
+ "passed": ssim >= 0.98 && delta_e <= 1.0 && delta_e95 <= 3.0,
+ }));
+ }
+ let passed = !cases.is_empty()
+ && cases
+ .iter()
+ .all(|case| case["passed"].as_bool() == Some(true));
+ serde_json::json!({
+ "passed": passed,
+ "scale": scale,
+ "os": std::env::consts::OS,
+ "cases": cases,
+ })
+}
+
fn to_rgba_image(image: &Rgba) -> image::RgbaImage {
let bytes = image
.pixels
@@ -198,8 +441,14 @@ fn crop_to(image: &image::RgbaImage, width: u32, height: u32) -> image::RgbaImag
}
let x = image.width().saturating_sub(width) / 2;
let y = image.height().saturating_sub(height) / 2;
- image::imageops::crop_imm(image, x, y, width.min(image.width()), height.min(image.height()))
- .to_image()
+ image::imageops::crop_imm(
+ image,
+ x,
+ y,
+ width.min(image.width()),
+ height.min(image.height()),
+ )
+ .to_image()
}
fn scaled(shape: &Shape, scale: f32) -> Shape {
diff --git a/apps/desktop-gpui/src/ui/glass.rs b/apps/desktop-gpui/src/ui/glass.rs
index b444f67cb..6194a92b0 100644
--- a/apps/desktop-gpui/src/ui/glass.rs
+++ b/apps/desktop-gpui/src/ui/glass.rs
@@ -30,8 +30,8 @@ struct Presets {
fn presets() -> &'static Presets {
static PRESETS: OnceLock<Presets> = OnceLock::new();
PRESETS.get_or_init(|| {
- let all: serde_json::Value = serde_json::from_str(cap_glass::PRESETS_JSON)
- .expect("glass presets are valid JSON");
+ let all: serde_json::Value =
+ serde_json::from_str(cap_glass::PRESETS_JSON).expect("glass presets are valid JSON");
let get = |name: &str| -> GlassMaterial {
serde_json::from_value(all[name].clone()).expect("glass preset is complete")
};
@@ -70,16 +70,32 @@ pub fn gpui_style(style: &PaneStyle) -> gpui::GlassStyle {
glow: style.glow,
glow_width: style.glow_width,
hairline: style.hairline,
+ tint_scale: style.tint.scale,
+ tint_luma: style.tint.luma,
+ tint_offset: style.tint.offset,
pad: 0.,
}
}
-pub fn paint(window: &mut Window, bounds: Bounds<Pixels>, radius: f32, material: &GlassMaterial) {
+/// A tint for a pane, sRGB with alpha, as SwiftUI's `.tint` takes it:
+/// Regular glass reads only its alpha, Clear glass its colour too.
+pub type Tint = gpui::Rgba;
+
+pub fn paint(
+ window: &mut Window,
+ bounds: Bounds<Pixels>,
+ radius: f32,
+ material: &GlassMaterial,
+ tint: Option<Tint>,
+) {
let (width, height) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
if width <= 0. || height <= 0. {
return;
}
- let style = material.resolve(width, height);
+ let mut style = material.resolve(width, height);
+ if let Some(tint) = tint {
+ style.tint = material.tint_matrix([tint.r, tint.g, tint.b], tint.a);
+ }
let radius = radius.min(width / 2.).min(height / 2.);
window.paint_glass(
bounds,
@@ -93,11 +109,20 @@ pub fn paint(window: &mut Window, bounds: Bounds<Pixels>, radius: f32, material:
/// everything added after it paints on the glass. `radius` is clamped to the
/// pane like CSS clamps `border-radius`.
pub fn pane(kind: GlassKind, dark: bool, radius: f32) -> Div {
+ pane_with(kind, dark, radius, None)
+}
+
+/// [`pane`] with a tint.
+pub fn pane_tinted(kind: GlassKind, dark: bool, radius: f32, tint: Tint) -> Div {
+ pane_with(kind, dark, radius, Some(tint))
+}
+
+fn pane_with(kind: GlassKind, dark: bool, radius: f32, tint: Option<Tint>) -> Div {
let material = *material(kind, dark);
div().relative().rounded(px(radius)).child(
canvas(
|_, _, _| {},
- move |bounds, _, window, _| paint(window, bounds, radius, &material),
+ move |bounds, _, window, _| paint(window, bounds, radius, &material, tint),
)
.absolute()
.top_0()
diff --git a/scripts/glass-reference/sweep.swift b/scripts/glass-reference/sweep.swift
new file mode 100644
index 000000000..15cea806a
--- /dev/null
+++ b/scripts/glass-reference/sweep.swift
@@ -0,0 +1,267 @@
+// Sweeps Apple's glass (NSGlassEffectView) across backdrop brightness and
+// pane size, so Cap's glass can match how Apple's adapts: small Regular
+// panes lighten over bright content in dark mode, and tints are tone mapped
+// against what is behind them. Writes <out>/scenes/<scene>.png,
+// <out>/apple/<case>.png and <out>/manifest.json in the same format as
+// reference.swift.
+//
+// swiftc -O sweep.swift -o sweep && ./sweep <out dir> [lens | tints]
+//
+// `lens` swaps the greys for the UV ramp (red and green encode the sampled
+// point), so the same shapes show how Apple's refraction scales with size.
+// `tints` runs a grid of tint colours and alphas over three greys, to fit
+// how a tint's colour and alpha set the tinted glass. `levels` runs Clear
+// glass only, under tints spanning their brightest and darkest channel,
+// which is what sets how a tint darkens over dark content. `hsl` runs Clear
+// glass under a regular grid of HSL lightness and saturation at one hue:
+// the tint keeps its hue, so this grid is the whole law.
+//
+// Each style and appearance keeps the same views for a rising and then a
+// falling pass over the greys, so any hysteresis in the adaptation shows up
+// as a difference between the `up` and `down` captures of a level.
+import AppKit
+import Metal
+
+let canvas = NSSize(width: 960, height: 600)
+
+struct Shape {
+ let name: String
+ let rect: NSRect
+ let radius: CGFloat
+}
+
+var shapes: [Shape] = []
+do {
+ // Capsules of one width and rising height.
+ var y: CGFloat = 20
+ for height in [20, 28, 36, 44, 52, 64, 80, 96] as [CGFloat] {
+ shapes.append(Shape(name: "capsule\(Int(height))", rect: NSRect(x: 30, y: y, width: 200, height: height), radius: height / 2))
+ y += height + 18
+ }
+ // Squares with a fixed corner radius.
+ y = 20
+ for side in [24, 32, 48, 64, 96, 128] as [CGFloat] {
+ shapes.append(Shape(name: "square\(Int(side))", rect: NSRect(x: 270, y: y, width: side, height: side), radius: min(12, side / 2)))
+ y += side + 18
+ }
+ // Bars of one height and rising width, then a large panel.
+ y = 20
+ for width in [60, 120, 240, 420] as [CGFloat] {
+ shapes.append(Shape(name: "bar\(Int(width))", rect: NSRect(x: 460, y: y, width: width, height: 44), radius: 22))
+ y += 44 + 18
+ }
+ shapes.append(Shape(name: "panel", rect: NSRect(x: 460, y: 300, width: 460, height: 270), radius: 24))
+}
+
+let greys: [Int] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]
+let styles: [(String, NSGlassEffectView.Style)] = [("regular", .regular), ("clear", .clear)]
+let appearances: [(String, NSAppearance.Name)] = [("light", .aqua), ("dark", .darkAqua)]
+let tints: [(String, NSColor?, [Double])] = [
+ ("none", nil, []),
+ ("blue", NSColor.systemBlue.withAlphaComponent(0.6), [0.0, 0.533, 1.0, 0.6]),
+ ("red", NSColor.systemRed.withAlphaComponent(0.6), [1.0, 0.22, 0.235, 0.6]),
+ ("green", NSColor.systemGreen.withAlphaComponent(0.6), [0.204, 0.78, 0.349, 0.6]),
+ ("blue30", NSColor.systemBlue.withAlphaComponent(0.3), [0.0, 0.533, 1.0, 0.3]),
+ ("blue100", NSColor.systemBlue, [0.0, 0.533, 1.0, 1.0]),
+]
+
+final class FlippedView: NSView {
+ override var isFlipped: Bool { true }
+}
+
+func greyImage(_ level: Int, scale: CGFloat) -> CGImage {
+ let width = Int(canvas.width * scale), height = Int(canvas.height * scale)
+ let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
+ let v = CGFloat(level) / 255
+ ctx.setFillColor(CGColor(srgbRed: v, green: v, blue: v, alpha: 1))
+ ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ return ctx.makeImage()!
+}
+
+func uvImage(scale: CGFloat) -> CGImage {
+ let width = Int(canvas.width * scale), height = Int(canvas.height * scale)
+ let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
+ for row in 0..<height {
+ for col in 0..<width {
+ ctx.setFillColor(CGColor(srgbRed: CGFloat(col) / CGFloat(width - 1),
+ green: CGFloat(row) / CGFloat(height - 1), blue: 0.5, alpha: 1))
+ ctx.fill(CGRect(x: col, y: row, width: 1, height: 1))
+ }
+ }
+ return ctx.makeImage()!
+}
+
+func writePNG(_ image: CGImage, to url: URL) {
+ let rep = NSBitmapImageRep(cgImage: image)
+ try! rep.representation(using: .png, properties: [:])!.write(to: url)
+}
+
+func capture(_ window: NSWindow, to url: URL) {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
+ process.arguments = ["-x", "-o", "-l\(window.windowNumber)", url.path]
+ try! process.run()
+ process.waitUntilExit()
+ let convert = Process()
+ convert.executableURL = URL(fileURLWithPath: "/usr/bin/sips")
+ convert.arguments = ["--matchTo", "/System/Library/ColorSync/Profiles/sRGB Profile.icc", url.path]
+ convert.standardOutput = FileHandle.nullDevice
+ try! convert.run()
+ convert.waitUntilExit()
+}
+
+func pump(_ seconds: TimeInterval) {
+ RunLoop.current.run(until: Date().addingTimeInterval(seconds))
+}
+
+let out = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "glass-sweep")
+let lensMode = CommandLine.arguments.count > 2 && CommandLine.arguments[2] == "lens"
+let hslMode = CommandLine.arguments.count > 2 && CommandLine.arguments[2] == "hsl"
+let levelsMode = hslMode || (CommandLine.arguments.count > 2 && CommandLine.arguments[2] == "levels")
+let tintMode = levelsMode || (CommandLine.arguments.count > 2 && CommandLine.arguments[2] == "tints")
+let tintGrid: [(String, NSColor?, [Double])] = {
+ var grid: [(String, NSColor?, [Double])] = [("none", nil, [])]
+ func add(_ name: String, _ r: Double, _ g: Double, _ b: Double, _ a: Double) {
+ grid.append((name, NSColor(srgbRed: r, green: g, blue: b, alpha: a), [r, g, b, a]))
+ }
+ for i in 0..<12 {
+ let color = NSColor(calibratedHue: CGFloat(i) / 12, saturation: 1, brightness: 1, alpha: 1).usingColorSpace(.sRGB)!
+ add("hue\(i * 30)", Double(color.redComponent), Double(color.greenComponent), Double(color.blueComponent), 0.6)
+ }
+ add("white", 1, 1, 1, 0.6)
+ add("grey50", 0.5, 0.5, 0.5, 0.6)
+ add("black", 0, 0, 0, 0.6)
+ add("navy", 0.1, 0.15, 0.45, 0.6)
+ add("brown", 0.55, 0.35, 0.2, 0.6)
+ add("pastel", 0.95, 0.75, 0.85, 0.6)
+ for a in [0.1, 0.2, 0.45, 0.8, 1.0] {
+ add("orange\(Int(a * 100))", 1, 0.58, 0.0, a)
+ }
+ if levelsMode {
+ grid = [("none", nil, [])]
+ for high in [0.2, 0.4, 0.6, 0.8, 1.0] {
+ for fraction in [0.0, 0.25, 0.5, 0.75] {
+ let low = high * fraction
+ add("warm\(Int(high * 100))-\(Int(fraction * 100))", high, low + (high - low) * 0.3, low, 0.6)
+ add("cool\(Int(high * 100))-\(Int(fraction * 100))", low, low + (high - low) * 0.6, high, 0.6)
+ }
+ add("grey\(Int(high * 100))", high, high, high, 0.6)
+ }
+ }
+ if hslMode {
+ grid = [("none", nil, [])]
+ // HSL to sRGB at hue 210 degrees: red is the darkest channel, blue
+ // the brightest, green halfway between.
+ for lightness in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0] {
+ for saturation in [0.0, 0.25, 0.5, 0.75, 1.0] {
+ let chroma = (1 - abs(2 * lightness - 1)) * saturation
+ let low = lightness - chroma / 2
+ let high = lightness + chroma / 2
+ add("l\(Int(lightness * 100))-s\(Int(saturation * 100))", low, (low + high) / 2, high, 0.6)
+ }
+ }
+ }
+ return grid
+}()
+try FileManager.default.createDirectory(at: out.appendingPathComponent("scenes"), withIntermediateDirectories: true)
+try FileManager.default.createDirectory(at: out.appendingPathComponent("apple"), withIntermediateDirectories: true)
+
+let app = NSApplication.shared
+app.setActivationPolicy(.regular)
+app.finishLaunching()
+
+let window = NSWindow(contentRect: NSRect(origin: NSPoint(x: 80, y: 80), size: canvas),
+ styleMask: [.borderless], backing: .buffered, defer: false)
+window.isOpaque = true
+window.colorSpace = .sRGB
+window.hasShadow = false
+window.level = .floating
+let root = FlippedView(frame: NSRect(origin: .zero, size: canvas))
+window.contentView = root
+window.makeKeyAndOrderFront(nil)
+app.activate(ignoringOtherApps: true)
+pump(1.0)
+
+let scale = window.backingScaleFactor
+let backdrop = NSImageView(frame: root.bounds)
+backdrop.imageScaling = .scaleAxesIndependently
+root.addSubview(backdrop)
+
+// Scene names by level; the lens mode has one scene, the UV ramp.
+var images: [Int: NSImage] = [:]
+var sceneNames: [Int: String] = [:]
+let levels: [Int] = lensMode ? [-1] : tintMode ? [16, 128, 240] : greys
+for level in levels {
+ let image = level < 0 ? uvImage(scale: scale) : greyImage(level, scale: scale)
+ let scene = level < 0 ? "uv" : String(format: "grey%03d", level)
+ writePNG(image, to: out.appendingPathComponent("scenes/\(scene).png"))
+ images[level] = NSImage(cgImage: image, size: canvas)
+ sceneNames[level] = scene
+}
+
+var cases: [[String: Any]] = []
+let runTints = lensMode ? Array(tints.prefix(1)) : tintMode ? tintGrid : tints
+for (tintName, tint, _) in runTints {
+ for (styleName, style) in styles {
+ for (appearanceName, appearance) in appearances {
+ // Clear's tint does not depend on the appearance, so the grid
+ // only needs Clear in light mode.
+ if tintMode && styleName == "clear" && appearanceName == "dark" {
+ continue
+ }
+ if levelsMode && styleName == "regular" {
+ continue
+ }
+ window.appearance = NSAppearance(named: appearance)
+ backdrop.image = images[levels[0]]
+ var views: [NSView] = []
+ for shape in shapes {
+ let glass = NSGlassEffectView(frame: shape.rect)
+ glass.style = style
+ glass.cornerRadius = shape.radius
+ glass.tintColor = tint
+ root.addSubview(glass)
+ views.append(glass)
+ }
+ pump(1.0)
+ // Untinted runs go up and back down to expose hysteresis; tinted
+ // ones only go up.
+ let passes: [(String, [Int])] = tintName == "none" && !lensMode && !tintMode
+ ? [("up", levels), ("down", levels.reversed())]
+ : [("up", levels)]
+ for (pass, levels) in passes {
+ for level in levels {
+ backdrop.image = images[level]
+ pump(1.0)
+ let scene = sceneNames[level]!
+ let name = "\(scene)-\(styleName)-\(appearanceName)-\(tintName)-\(pass)"
+ capture(window, to: out.appendingPathComponent("apple/\(name).png"))
+ cases.append([
+ "name": name, "scene": scene, "style": styleName,
+ "appearance": appearanceName, "tint": tintName, "pass": pass,
+ ])
+ }
+ }
+ views.forEach { $0.removeFromSuperview() }
+ }
+ }
+}
+
+let manifest: [String: Any] = [
+ "canvas": [canvas.width, canvas.height],
+ "scale": scale,
+ "os": ProcessInfo.processInfo.operatingSystemVersionString,
+ "reduceTransparency": NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency,
+ "increaseContrast": NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast,
+ "gpu": MTLCreateSystemDefaultDevice()?.name ?? "none",
+ "shapes": shapes.map { ["name": $0.name, "rect": [$0.rect.minX, $0.rect.minY, $0.rect.width, $0.rect.height], "radius": $0.radius] },
+ "tints": Dictionary(uniqueKeysWithValues: runTints.filter { !$0.2.isEmpty }.map { ($0.0, $0.2) }),
+ "cases": cases,
+]
+let data = try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys])
+try data.write(to: out.appendingPathComponent("manifest.json"))
+print("wrote \(cases.count) cases to \(out.path)")