金属-片段着色器产生噪音

问题描述

我正在尝试使用Metal By Tutorials中描述的基本照明技术在模型上产生散射光,环境光和镜面光。

我已经多次使用这种照明算法,并且效果很好,但是过去2倍的镜面反射颜色似乎会产生特征性的绿色和黄色噪声。即使没有镜面反射色,漫反射色和环境色也似乎会产生这种可怕的噪声。

关于为什么会发生这种情况的任何想法吗?

我想知道我不使用渲染器类的事实是否会导致此问题。

这是片段着色器代码

fragment float4 fragmentmain(const VOUT in [[stage_in]],texture2d<float> texture1 [[texture(0)]],constant FRAGMENTUNIFORMS &data [[buffer(2)]],constant LIGHT *lights [[buffer(3)]])
{
     constexpr sampler texturesampler;
     
     float3 basecolor = texture1.sample(texturesampler,in.coords).rgb;
     float3 diffusecolor;
     float3 ambientcolor;
     float3 specularcolor;
     float3 materialspecularcolor = float3(1,1,1);
     float shine = 32;
     float3 normaldirection = normalize(in.normal);
     
     for (uint i = 0 ; i < data.lightcount ; i++) {
          LIGHT light = lights[i];
          if (light.type == sun) {
               float3 lightdirection = normalize(-light.position);
               float diffuseintensity = saturate(-dot(lightdirection,normaldirection));
               diffusecolor = light.color * basecolor * diffuseintensity;
               
               if (diffuseintensity > 0) {
                    float3 reflection = reflect(lightdirection,normaldirection);
                    float3 cameradirection = normalize(in.position.xyz - data.cameraposition);
                    float specularintensity = pow(saturate(-dot(reflection,cameradirection)),shine);
                    specularcolor = light.color * materialspecularcolor * specularintensity;
               }
          } else if (light.type == ambient) {
               ambientcolor = light.color * light.intensity;
          }
     }
     
     float3 color = diffusecolor + ambientcolor + specularcolor;
     return float4(color,1);
}

Noise

解决方法

有趣的解决方案。

我更改了:

float3 diffusecolor;
float3 ambientcolor;
float3 specularcolor;

float3 diffusecolor = float3(0,0);
float3 ambientcolor = float3(0,0);
float3 specularcolor = float3(0,0);

,图像完全变黑。没有更多的噪音。但是,似乎在for循环中没有迭代我的灯光。

原来,我的light.type枚举设置为

enum LIGHTTYPE {
     sun = 1,ambient = 2
};

但是当我将其更改为:

enum LIGHTTYPE {
     sun = 0,ambient = 1
};

问题已完全解决。抱歉!