像素抖动(Pixel Dithering) 的Shader实现

莫列波纹(Moiré pattern)与Banding有时候会会对图像画面造成显示问题,如此文所示:

莫列波纹(Moiré pattern)与Banding_moir茅 patterns-CSDN博客

在实时渲染中,用Shader实现的Dithering能缓解这类问题。

没有dithering效果(Banding现象):

像素抖动(Pixel Dithering) 的Shader实现_第1张图片

使用dithering效果(Smooth):

像素抖动(Pixel Dithering) 的Shader实现_第2张图片

这里给出HLSL, GLSL, WGSL这些环境下的Pixel Dithering Shader实现。具体细节再具体调整。

DirectX中实现的Dithering实现:

static const float PI = 3.141592653589793;
static const float factor = 0.25 / 255.0;
static const float c = 43758.5453;
static const float2 uvFactor = float2( 12.9898 ,78.233 );
float randUV( float2 uv ) {
    float dt = dot( uv.xy, uvFactor );
    float sn = fmod( dt, PI );
    return frac(sin(sn) * c);
}

static const float4 dither_fector = float4( factor, -factor, factor, factor);
float4 dithering( float4 color, float2 puv ) {
    float grid_position = randUV( puv );
    return color + lerp( 2.0 * dither_fector, -2.0 * dither_fector, grid_position );
}

// ps shader
float4 PS(VertexOut pIn) : SV_Target
{
    float4 color = pIn.color;
    color = dithering(color, pIn.posH.xy);
    return color;
}

Opengl(ES)/WebGL中实现的Dithering:

const float PI = 3.14159265359;
const float factor = 0.25 / 255.0;
const float c = 43758.5453;
const vec2 uvFactor = vec2( 12.9898 ,78.233 );
float randUV( vec2 uv ) {
    float dt = dot( uv.xy, uvFactor );
    float sn = mod( dt, PI );
    return fract(sin(sn) * c);
}
const vec4 dither_fector = vec4( factor, -factor, factor, factor);
vec4 dithering( vec4 color, vec2 puv ) {
    float grid_position = randUV( puv );
    return color + mix( 2.0 * dither_fector, -2.0 * dither_fector, grid_position );
}
// 使用伪代码样例
// void main() {
//     FragColor0 = dithering(FragColor0, gl_FragCoord.xy);
// }

WGSL中实现的Dithering:

 https://github.com/vilyLei/voxwebgpu/blob/feature/material/src/voxgpu/sample/VertColorRect.ts

struct VSOut {
    @builtin(position) Position: vec4,
    @location(0) color: vec3,
    @location(1) pos: vec4,
};

@vertex
fn main(@location(0) inPos: vec3,
        @location(1) inColor: vec3) -> VSOut {
    var vsOut: VSOut;
    vsOut.Position = vec4(inPos, 1.0);
    vsOut.color = inColor;
    vsOut.pos = vsOut.Position;
    return vsOut;
}

const PI = 3.14159265359;
const factor = 0.25 / 255.0;
const c = 43758.5453;
const uvFactor = vec2( 12.9898 ,78.233 );
fn randUV( uv: vec2 ) -> f32{
    let dt = dot( uv.xy, uvFactor );
    let sn = modf( dt / PI ).fract;
    return fract(sin(sn) * c);
}
const dither_fector = vec4( factor, -factor, factor, factor);
fn dithering( color: vec4, puv: vec2 ) -> vec4 {
    let grid_position = randUV( puv );
    return color + mix( 2.0 * dither_fector, -2.0 * dither_fector, grid_position );
}

@fragment
fn main(
	@location(0) inColor: vec3,
	@location(1) pos: vec4
	) -> @location(0) vec4 {
    return dithering(vec4(inColor, 1.0), pos.xy);
}

你可能感兴趣的:(DirectX,WebGL/WebGPU,3D引擎,3d,抖动算法,dithering,shader)