XNA - Render texture to a rendertarget 2d via SpriteBatch error

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 5:41 UTC
Read the original article Hit count: 371

Filed under:
|

I got 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 Draw(GameTime gameTime). First drawScene is called, then drawPostProcessing is called.

The thing is, I can't run the code because "the render target must not be set on the device when it is used as a texture."

at line spriteBatch.Draw(targetScene, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White);

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

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#