将参数传递给SlimDX Direct3D 11中的常量缓冲区

时间:2011-02-16 13:53:09

标签: c# buffer direct3d shader slimdx

这与Setting up the constant buffer using SlimDX

有关

我有一个着色器,非常简单,看起来像这样:

cbuffer ConstantBuffer : register(b0)
{
    float4 color;
}

float4 VShader(float4 position : POSITION) : SV_POSITION
{
    return position;
}

float4 PShader(float4 position : SV_POSITION) : SV_Target
{
    return color;
}

所有这一切都是将通过常量缓冲区传入的颜色应用于绘制的每个像素,非常简单。

在我的代码中,我按如下方式定义了我的常量缓冲区:

[StructLayout(LayoutKind.Explicit)]
        struct ConstantBuffer
        {
            [FieldOffset(0)]
            public Color4 Color;
        }

并在我的渲染循环中设置它。

ConstantBuffer cb = new ConstantBuffer();
cb.Color = new Color4(Color.White);
using (DataStream data = new DataStream(Marshal.SizeOf(typeof(ConstantBuffer)), true, true))           
{
    data.Write(cb);
    data.Position = 0;
    D3D.Buffer buffer = new D3D.Buffer(device,data, new BufferDescription
    {
        Usage = ResourceUsage.Default,
        SizeInBytes = Marshal.SizeOf(typeof(ConstantBuffer)),
        BindFlags = BindFlags.ConstantBuffer
    });
    context.UpdateSubresource(new DataBox(0, 0, data), buffer, 0);
}

context是我的设备.ImmediateContext和设备是我的Direct3D设备。然而,当它运行时,它将我的像素绘制为黑色,尽管已经通过了白色,所以很明显没有设置值。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你必须创建一次D3D.Buffer对象,根据需要随时更新它(你将初始数据指定为构造函数参数,所以如果你总是有一个白色对象,就没有必要调用UpdateSubresource (根本),并在发出绘制调用之前将其绑定到管道(context.PixelShader.SetConstantBuffer(buffer, 0))。