【问题标题】:Textures do not get accessed properly in pixel shader (DirectX11)在像素着色器 (DirectX11) 中无法正确访问纹理
【发布时间】:2021-04-07 06:39:13
【问题描述】:

像素着色器未正确使用纹理。我在我的像素着色器中加载了两个单独的纹理。但是,大多数时候,我只能显示 Texture1,即使我尝试显示 Texture2。

Texture2D Texture1;
Texture2D Texture2;

SamplerState ss;

float4 main(float4 position: SV_POSITION, float4 color: COLOR, float2 texCoord: TEXCOORD) : SV_TARGET
{
    float4 color1 = Texture1.Sample(ss, texCoord);
    float4 color2 = Texture2.Sample(ss, texCoord);
    
    // even though color2 is specified here, color1 ie Texture1 is still displayed
    float4 finalColor = color2;
    
    return finalColor;
}

上面的代码总是显示纹理 1(砖块): texture 1

奇怪的是,我可以显示第二个纹理,但前提是我将像素着色器修改为如下所示:

float4 main(float4 position: SV_POSITION, float4 color: COLOR, float2 texCoord: TEXCOORD) : SV_TARGET
{
    float4 color1 = Texture1.Sample(ss, texCoord);
    float4 color2 = Texture2.Sample(ss, texCoord);
    float4 finalColor = {0,0,0,0};
    if (color1.z != color2.z) {
        // no idea why, but setting finalColor to color2 outside of this if statement
        // doesn't work.
        finalColor = color2;
    }

    return finalColor;
}

这会显示第二个纹理(木头):texture 2

这是加载纹理的代码:

    // load the texture
    HRESULT hr = CreateWICTextureFromFile(m_dev.Get(), nullptr, L"bricks.png", nullptr, &m_texture1, 0);
    hr = CreateWICTextureFromFile(m_dev.Get(), nullptr, L"wood.png", nullptr, &m_texture2, 0);

    ...
    m_devCon->PSSetShaderResources(0, 1, m_texture1.GetAddressOf());
    m_devCon->PSSetShaderResources(1, 1, m_texture2.GetAddressOf());

这里发生了什么?我知道两个纹理都加载到像素着色器中,因为如果我使用这个奇怪的 hack,我可以获得第二个纹理来显示。

【问题讨论】:

  • 尝试使用显式绑定:Texture2D<float4> Texture1 : register(t0); Texture2D<float4> Texture2 : register(t1); sampler ss : register(s0).
  • @ChuckWalbourn 成功了,现在我的颜色可以正常改变了!谢谢 您能否发表您的评论作为答案,以便我将其标记为正确?也许更详细地说明为什么这可以解决问题?

标签: shader directx-11 hlsl pixel-shader


【解决方案1】:

HLSL 中的这些声明声明了两个纹理槽和一个采样器槽,但它们并没有指出它们绑定的位置。正如声明的那样,您必须使用着色器反射来确定这一点,例如通过旧的Effects 系统。

Texture2D Texture1;
Texture2D Texture2;

SamplerState ss;

为了使用显式绑定,您需要指明每个项目绑定到哪个插槽。在纹理中显式声明预期的通道数也是一种很好的形式(在这种情况下,我假设有 4 个通道):

Texture2D<float4> Texture1 : register(t0);
Texture2D<float4> Texture2 : register(t1);

SamplerState ss : register(s0);

由于您的代码实际上并未显示为使用CreateSamplerState 创建采样器并使用PSSetSamplers 将其绑定到0 槽,因此您依赖于Microsoft DocsD3D11_FILTER_MIN_MAG_MIP_LINEAR 中的“默认”采样器状态D3D11_TEXTURE_ADDRESS_CLAMP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多