我正在尝试在HLSL中为XNA项目创建动画太阳。
我正在使用从这个站点学到的Perlin Noise算法在像素着色器中生成它的纹理。
这是我为像素着色器编写的 hlsl 代码:
sampler myTexture;
struct VS_Output{
float4 Position : POSITION0;
float4 Color : COLOR0;
float2 TextCoord : TEXCOORD0;
};
float CosineInterpolation( float x, float y, float fractional ) {
float ft = 3.141592f * fractional;
float f = ( 1.0f - cos( ft ) ) * 0.5f;
return x * ( 1.0f - f ) + y * f;
}
float Noise(float2 xy)
{
float2 noise = (frac(sin(dot(xy ,float2(12.9898,78.233)*2.0)) * 43758.5453));
return abs(noise.x + noise.y) * 0.5;
}
float SmoothNoise( float integer_x, float integer_y ) {
float corners = ( Noise( float2(integer_x - 1, integer_y - 1) ) + Noise( float2(integer_x + 1, integer_y + 1 )) + Noise( float2(integer_x + 1, integer_y - 1 )) + Noise( float2(integer_x - 1, integer_y + 1 )) ) / 16.0f;
float sides = ( Noise( float2(integer_x, integer_y - 1 )) + Noise( float2(integer_x, integer_y + 1 )) + Noise( float2(integer_x + 1, integer_y )) + Noise( float2(integer_x - 1, integer_y )) ) / 8.0f;
float center = Noise( float2(integer_x, integer_y )) / 4.0f;
return corners + sides + center;
}
float InterpolatedNoise( float x, float y ) {
float integer_x = x - frac(x), fractional_x = frac(x);
float integer_y = y - frac(y), fractional_y = frac(y);
float p1 = SmoothNoise( integer_x, integer_y );
float p2 = SmoothNoise( integer_x + 1, integer_y );
float p3 = SmoothNoise( integer_x, integer_y + 1 );
float p4 = SmoothNoise( integer_x + 1, integer_y + 1 );
p1 = CosineInterpolation( p1, p2, fractional_x );
p2 = CosineInterpolation( p3, p4, fractional_x );
return CosineInterpolation( p1, p2, fractional_y );
}
float CreatePerlinNoise( float x, float y ) {
float result = 0.0f, amplitude = 0.0f, frequency = 0.0f, persistance = 0.1f;
for ( int i = 1; i <= 4; i++ ) {
frequency += 2;
amplitude += persistance;
result += InterpolatedNoise( x * frequency, y * frequency ) * amplitude;
}
return result;
}
float4 ps_main(VS_Output Input) : COLOR0
{
float index = CreatePerlinNoise(Input.TextCoord.x*256.0f, Input.TextCoord.y*256.0f);
return tex2D(myTexture, index);
}
基本上,在这段代码中,通过将纹理坐标分量 ( TextCoord
) 传递给CreatePelinNoise
函数,它返回一个用作渐变纹理颜色索引的值 ( myTexture
1px x 256px ):
AMD RenderMonkey中的结果如下:
但是在球体的两极有一个难看的不需要的效果,这使得生成的纹理不均匀:
如何解决这个问题并使生成的纹理均匀?