XNA - Error while rendering a texture to a 2D render target via SpriteBatch

Posted by Jared B on Game Development See other posts from Game Development or by Jared B
Published on 2012-04-04T00:42:06Z Indexed on 2012/04/04 17:43 UTC
Read the original article Hit count: 362

Filed under:
|
|
|

I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D:

private void drawScene(GameTime g)
{
    GraphicsDevice.Clear(skyColor);
    GraphicsDevice.SetRenderTarget(targetScene);
    drawSunAndMoon();
    effect.Fog = true;
    GraphicsDevice.SetVertexBuffer(line);
    effect.MainEffect.CurrentTechnique.Passes[0].Apply();
    GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
    GraphicsDevice.SetRenderTarget(null);
    SceneTexture = targetScene;
}

private void drawPostProcessing(GameTime g)
{
    effect.SceneTexture = SceneTexture;
    GraphicsDevice.SetRenderTarget(targetBloom);
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null);
    {
        if (Bloom) effect.BlurEffect.CurrentTechnique.Passes[0].Apply();
        spriteBatch.Draw(
            targetScene,
            new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
            Color.White);
    }
    spriteBatch.End();
    BloomTexture = targetBloom;
    GraphicsDevice.SetRenderTarget(null);
}

Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called.

The thing is, when I run this code I get an error on the spriteBatch.Draw call:

The render target must not be set on the device when it is used as a texture.

I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target.

However, to my knowledge, the only way of doing this is to write:

GraphicsDevice.SetRenderTarget(outputTarget)
SpriteBatch.Draw(inputTarget, ...)
GraphicsDevice.SetRenderTarget(null)

Which encounters the same exact problem I'm having right now.

So, the question I'm asking is: how would I render inputTarget to outputTarget without reference issues?

© Game Development or respective owner

Related posts about XNA

Related posts about c#