我正在创建一个XNA游戏,可以从多个精灵中创建随机岛屿。它在一个单独的线程中创建它们,然后使用RenderTarget2D将它们编译为单个纹理。
要创建我的RenderTarget2D,我需要一个图形设备。如果我使用自动创建的图形设备,大多数情况下工作正常,除了主游戏线程中的绘制调用与之冲突。在图形设备上使用lock()会导致闪烁,即使这样,有时也无法正确创建纹理。
如果我创建自己的图形设备,没有冲突,但岛屿永远不会正确渲染,而是出现纯黑色和白色。我不知道为什么会这样。基本上我需要一种方法来创建第二个图形设备,让我得到相同的结果,而不是黑/白。有人有任何想法吗?
这是我用来尝试创建第二个图形设备的代码,供TextureBuilder专用:
var presParams = game.GraphicsDevice.PresentationParameters.Clone();
// Configure parameters for secondary graphics device
GraphicsDevice2 = new GraphicsDevice(game.GraphicsDevice.Adapter, GraphicsProfile.HiDef, presParams);
这是我用于将岛屿渲染为单个纹理的代码:
public IslandTextureBuilder(List<obj_Island> islands, List<obj_IslandDecor> decorations, SeaGame game, Vector2 TL, Vector2 BR, int width, int height)
{
gDevice = game.Game.GraphicsDevice; //default graphics
//gDevice = game.GraphicsDevice2 //created graphics
render = new RenderTarget2D(gDevice, width, height, false, SurfaceFormat.Color, DepthFormat.None);
this.islands = islands;
this.decorations = decorations;
this.game = game;
this.width = width;
this.height = height;
this.TL = TL; //top left coordinate
this.BR = BR; //bottom right coordinate
}
public Texture2D getTexture()
{
lock (gDevice)
{
//Set render target. Clear the screen.
gDevice.SetRenderTarget(render);
gDevice.Clear(Color.Transparent);
//Point camera at the island
Camera cam = new Camera(gDevice.Viewport);
cam.Position = TL;
cam.Update();
//Draw all of the textures to render
SpriteBatch batch = new SpriteBatch(gDevice);
batch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.Transform);
{
foreach (obj_Island island in islands)
{
island.Draw(batch);
}
foreach (obj_IslandDecor decor in decorations)
{
decor.Draw(batch);
}
}
batch.End();
//Clear render target
gDevice.SetRenderTarget(null);
//Copy to texture2D for permanant storage
Texture2D texture = new Texture2D(gDevice, render.Width, render.Height);
Color[] color = new Color[render.Width * render.Height];
render.GetData<Color>(color);
texture.SetData<Color>(color);
Console.WriteLine("done");
return texture;
}
这是应该发生的事情,具有透明背景(通常如果我使用默认设备) http://i110.photobucket.com/albums/n81/taumonkey/GoodIsland.png
当默认设备发生冲突且主线程设法调用Clear()时(即使它也被锁定),会发生这种情况 NotSoGoodIsland.png(需要10个声望....)
这是我使用自己的图形设备时会发生什么 http://i110.photobucket.com/albums/n81/taumonkey/BadIsland.png
提前感谢您提供的任何帮助!
答案 0 :(得分:0)
我可能已经通过将RenderToTarget代码移动到Draw()方法并在第一次调用Draw()时从主线程中调用它来解决这个问题。