设置像素着色器均匀变量

时间:2016-07-19 12:22:04

标签: c# wpf shader pixel-shader

虚假的问题,我想。我有一个自定义着色器,如下所示:

sampler2D InputTexture;

float parameter1, parameter2 etc

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 result = blah-blah-blah some calculations using parameter1, parameter2 etc.

    return result;
}

我正试图通过看起来像这样的包装器来使用它:

class MyShaderEffect : ShaderEffect
{
    private PixelShader _pixelShader = new PixelShader();
    public readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(MyShaderEffect), 0);

    public MyShaderEffect()
    {
        _pixelShader.UriSource = new Uri("MyShader.ps", UriKind.Relative);
        this.PixelShader = _pixelShader;
        this.UpdateShaderValue(InputProperty);
    }

    public Brush Input
    {
        get { return (Brush)this.GetValue(InputProperty); }
        set { this.SetValue(InputProperty, value); }
    }
}

所以,我的问题是:如何从C#程序中设置这些着色器参数?

1 个答案:

答案 0 :(得分:1)

它就在ShaderEffect课程的documentation中。您需要为每个参数创建依赖项属性。例如:

class MyShaderEffect
{
    public MyShaderEffect()
    {
        PixelShader = _pixelShader;

        UpdateShaderValue(InputProperty);
        UpdateShaderValue(ThresholdProperty);
    }

    public double Threshold
    {
        get { return (double)GetValue(ThresholdProperty); }
        set { SetValue(ThresholdProperty, value); }
    }

    public static readonly DependencyProperty ThresholdProperty =
        DependencyProperty.Register("Threshold", typeof(double), typeof(MyShaderEffect),
                new UIPropertyMetadata(0.5, PixelShaderConstantCallback(0)));
}

0中的PixelShaderConstantCallback是指您在HLSL中使用的注册:

float threshold : register(c0);

这样,WPF知道在属性更改时更新着色器。在构造函数中调用UpdateShaderValue来初始传递值也很重要。