问题描述
我在片段着色器中有以下功能,但它将 fps 降低了 7
half3 ClusterandDithering(half3 color,half2 uv)
{
half2 clusters = half2(16,16);
color.xyz = RgbToHsv(color.xyz);
color.yz = round(color.yz * clusters);
half2 centerUV = half2(0,0);
centerUV.x = floor(uv.x * _BaseMap_TexelSize.z) / _BaseMap_TexelSize.z;
centerUV.y = ceil(uv.y * _BaseMap_TexelSize.w) / _BaseMap_TexelSize.w;
half2 UVDither = fmod(centerUV,_BaseMap_TexelSize.xy * 2) * _BaseMap_TexelSize.zw;
half Min = min(UVDither.x,UVDither.y);
half Odd = 1 - fmod(color.z,2);
half Val = color.z > clusters / 2 ? 0 : 1;
half Dither = Min * Odd * Val;
color.z = (color.z + Dither);
color.yz /= clusters;
color = HsvToRgb(color);
return color;
}
此代码减少了 SV chanel 变体和抖动(从 UV 中心制作网格)。 例如这里的最小值结果: 奇怪的: 瓦尔: 没有聚类或抖动: 抖动和聚类: 任何想法如何优化它?
更新: 稍微更改了代码(没有帮助,但看起来更好)。
half3 ClusterandDithering(half3 color,half2 uv)
{
half2 clusters = half2(8,8);
color.xyz = RgbToHsv(color.xyz);
color.yz = round(color.yz * clusters);
half2 centerUV = half2(0,0);
centerUV.x = floor(uv.x * _BaseMap_TexelSize.z);
centerUV.y = ceil(uv.y * _BaseMap_TexelSize.w);
centerUV = fmod(centerUV,2);
half Min = min(centerUV.x,centerUV.y);
half Odd = 1 - fmod(color.z,2);
half Val = color.z > clusters.y / 2 ? 0 : 1;
half Dither = Min * Odd * Val;
color.z = (color.z + Dither);
color.yz /= clusters;
color = HsvToRgb(color);
return color;
}
片段函数内部的使用:
half4 LitPassFragment(varyings input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(input.uv,surfaceData);
InputData inputData;
InitializeInputData(input,surfaceData.normalTS,inputData);
half4 color = UniversalFragmentPBR(inputData,surfaceData.albedo,surfaceData.Metallic,surfaceData.specular,surfaceData.smoothness,surfaceData.occlusion,surfaceData.emission,surfaceData.alpha);
color.rgb = ClusterandDithering(color.rgb,input.uv);
color.rgb = MixFog(color.rgb,inputData.fogCoord);
return color;
}
解决方法
终于找到自定义 function 将 RGB 转换为 HSV,反之亦然。它比 Unity 内置的要快。没有其他方法可以优化该代码,至少您知道如何使用一个函数对值进行乘法和除法。