2D光性能优化

时间:2013-11-19 00:16:59

标签: c# performance xna light

我目前正在尝试使用XNA WITHOUT HLSL实现简单的2D Lightning。问题是,我这样做的方式给了我巨大的fps下降。

        //Create a new array to store the texture pixels.
        Color[] colorData = new Color[this.backgroundAtual.Texture.Height * this.backgroundAtual.Texture.Width];
        //I copy to the colorData a blackened copy of the original pixeldata
        Array.Copy(this.backgroundAtual.usingData, colorData, colorData.Length);

        //Create a rectangle to reduce the area of the texture where I have to make changes
        rec = new Rectangle((int)(l[0].Position.X - l[0].Radius), (int)(l[0].Position.Y - l[0].Radius), (int)(l[0].Radius * 2), (int)(l[0].Radius * 2));

        //Find the intersecting rectangle
        int x1 = Math.Max(rec.X, this.backgroundAtual.Texture.Bounds.X);
        int x2 = Math.Min(rec.X + rec.Width, this.backgroundAtual.Texture.Bounds.X + this.backgroundAtual.Texture.Bounds.Width);
        int y1 = Math.Max(rec.Y, this.backgroundAtual.Texture.Bounds.Y);
        int y2 = Math.Min(rec.Y + rec.Height, this.backgroundAtual.Texture.Bounds.Y + this.backgroundAtual.Texture.Bounds.Height);

        //Cycle through the rectangle on the texture
        for (int y = y1; y < y2; ++y)
        {
            for (int x = x1; x < x2; ++x)
            {
                pos = new Vector2(x, y);
                //Set the intensity of the color based on the distance from the center of the light
                colorData[(y * this.backgroundAtual.Texture.Width) + x] = colorData[(y * this.backgroundAtual.Texture.Width) + x] * ((l[0].Intensity / Vector2.Distance(l[0].Position, pos)) + 1);
            }
        }

        //Use setdata on the texture I'm going to draw so I can see the changes.
        this.backgroundAtual.Texture.SetData(colorData);
        //Draw the texture
        renderer.Draw(this.backgroundAtual.Texture, drawPosition, Color.White);

l [0]是光。有没有办法提高这个过程的速度?如果没有,是否有其他方法可以在没有HLSL的情况下实施闪电?我目前正在使用XNA。对不起,如果我的问题不明确。英语不是我的母语。

提前致谢

1 个答案:

答案 0 :(得分:0)

我猜测有一个GetData来电,可能在你的usingData财产中。 GetDataSetData来电非常慢。如果这些调用在你的主循环中,你将丢帧,特别是如果纹理很大。在XNA中创建Texture2D并在其上调用Content.Load时,Texture2D的像素数据存储在vram中,并且将数据来回移动到cpu是一个相当慢的操作

不使用HLSL,我对2D灯光的最佳建议是在你想要光线的形状中创建一个Texture2D,不透明度朝向纹理的边缘变低。将您的场景渲染为RenderTarget,然后使用SpriteBatch.Draw混合使用灯光做另一个Additive