새소식

개발/Shader

[HLSL] Noise - Voronoi Shader

  • -

아래는 ShaderED에서 사용하기 위한 함수

float2 random2(float2 p)
{
	return frac(sin(float2(dot(p, float2(127.1f, 311.7f)), dot(p, float2(269.5f, 183.3f))))*43758.5453f);
}

float3 voronoiNoise(float2 uv, float scale, float2 resolution, float animateOffset)
{
	float3 color;
	float2 st = uv * (resolution.x/resolution.y) * scale;
	float2 i_st = floor(st);
	float2 f_st = frac(st);
	
	float m_dist = 1;
	
	for (int y=-1;y<=1;y++)
	{
		for(int x=-1;x<=1;x++)
		{
			float2 neighbor = float2(float(x),float(y));
			
			//	random position from current + neighbor
			float2 p = random2(i_st + neighbor);
			//	animate point
			p = .5f + .5f * sin(animateOffset + 6.2381f * p);
			
			//	vector between pixel and the pixel
			float2 diff = neighbor + p - f_st;
			float dist = length(diff);
			m_dist = min(m_dist, dist);
		}
	}
	//	draw the min distance
	color += m_dist;
	//	draw cell center
	return color;
}

 

아래는 언리얼엔진에서 사용하기 위해 묶어놓은 코드다.

struct AnimateVoronoi
{
    float2 random2(float2 p)
    {
        return frac(sin(float2(dot(p, float2(127.1f, 311.7f)), dot(p, float2(269.5f, 183.3f))))*43758.5453f);
    }

    float3 voronoiNoise(float2 uv, float scale, float2 resolution, float animateOffset)
    {
        float3 color = float3(0,0,0);
        float2 st = uv * (resolution.x/resolution.y) * scale;
        float2 i_st = floor(st);
        float2 f_st = frac(st);
        
        float m_dist = 1;
        
        for (int y=-1;y<=1;y++)
        {
            for(int x=-1;x<=1;x++)
            {
                float2 neighbor = float2(float(x),float(y));
                
                //	random position from current + neighbor
                float2 p = random2(i_st + neighbor);
                //	animate point
                p = .5f + .5f * sin(animateOffset + 6.2381f * p);
                
                //	vector between pixel and the pixel
                float2 diff = neighbor + p - f_st;
                float dist = length(diff);
                m_dist = min(m_dist, dist);
            }
        }
        //	draw the min distance
        color += m_dist;
        //	draw cell center
        return color;
    } 
};

AnimateVoronoi voronoi;
return voronoi.voronoiNoise(uv, scale, resolution, animateOffset);

 

원본 출처 : https://thebookofshaders.com/12/

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.