XNA - Error while rendering a texture to a 2D render target via SpriteBatch
- by Jared B
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?