RenderTargetView to ShaderResourceView

I come from XNA, where I could easily create a rendertarget and use it as a simple "Texture2D". I created a ID3D11RenderTargetView object and a ID3D11ShaderResourceView object. I draw my sprites to my render target, then want to use it as a ShaderResourceView to send it to a shader.

I tried Querying the rendertarget's interface like:

ID3D11ShaderResourceView *resource= NULL;
renderTargetobject->QueryInterface<ID3D11ShaderResourceView >(&resource);

the above code does not generate any usable value to the "resource" object, which I want to send to my shader every frame (I am trying to do a simple reflection).

Upvotes: 1

Views: 3934

Answers (1)

OK, finally figured it out. It turned out it would have been better to just follow a tutorial, than try to port my code from XNA. I wanted to do this by somehow "copying" the rendertarget resource to a shaderresourceview every frame, but turns out, if both of them are set up prior to rendering, they just need to be linked to the same texture2D resource, and the rendertarget will automatically write to that linked texture, and the shaderresourceview will automatically look it up when called.

So the code, if anyone cares:

//global declarations:
ID3D11Device*           g_pd3dDevice;
ID3D11DeviceContext*    g_pImmediateContext;

ID3D11Texture2D* refTex;
ID3D11RenderTargetView* refRen;
ID3D11ShaderResourceView* refRes;


void SetUp()
{
D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));

textureDesc.Width = SCREENWIDTH;
textureDesc.Height = SCREENHEIGHT;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;

g_pd3dDevice->CreateTexture2D(&textureDesc, NULL, &refTex);



D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
renderTargetViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
renderTargetViewDesc.Texture2D.MipSlice = 0;

g_pd3dDevice->CreateRenderTargetView(refTex, &renderTargetViewDesc, &refRen);



D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
shaderResourceViewDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;


g_pd3dDevice->CreateShaderResourceView(refTex, &shaderResourceViewDesc, &refRes);
}

void DrawToTexture()
{
g_pImmediateContext->OMSetRenderTargets(1, &refRen,NULL);
float ClearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
g_pImmediateContext->ClearRenderTargetView(refRen, ClearColor);

//then draw what you want to the target


}

Upvotes: 8

Related Questions