[OpenGL | C#]当glTexImage2D

时间:2016-12-29 00:46:08

标签: c# winapi opengl loading

当我尝试加载CubeMap时,我的程序崩溃了。

    public static int LoadCubemap(string name, int size)
    {
        string folder = @"Resources\Textures\" + name + @"\";
        int returnInt = GL.GenTexture();
        GL.BindTexture(TextureTarget.TextureCubeMap, returnInt);

        //bytesPerPixel * width * (height \ 6) * faceIndex
        updloadTexture(TextureTarget.TextureCubeMapPositiveX, Image.FromFile(folder + "xpos.png"), size);
        updloadTexture(TextureTarget.TextureCubeMapNegativeX, Image.FromFile(folder + "xneg.png"), size);
        updloadTexture(TextureTarget.TextureCubeMapPositiveY, Image.FromFile(folder + "ypos.png"), size);
        updloadTexture(TextureTarget.TextureCubeMapNegativeY, Image.FromFile(folder + "yneg.png"), size);
        updloadTexture(TextureTarget.TextureCubeMapPositiveZ, Image.FromFile(folder + "zpos.png"), size);
        updloadTexture(TextureTarget.TextureCubeMapNegativeZ, Image.FromFile(folder + "zneg.png"), size);

        int nearest = (int)TextureMagFilter.Nearest;
        GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, ref nearest);
        GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, ref nearest);

        GL.BindTexture(TextureTarget.TextureCubeMap, 0);

        return returnInt;
    }

    private static void updloadTexture(TextureTarget target, Image texture, int size)
    {
        GL.TexImage2D(TextureTarget.TextureCubeMapNegativeZ, 0, PixelInternalFormat.Rgb, size, size, 0, PixelFormat.Rgb, PixelType.UnsignedByte, imageToByteArray(texture));
    }

    public static byte[] imageToByteArray(Image image)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(image, typeof(byte[]));
    }

在调用GL.TexImage2D时第3次或第4次崩溃。我无法找到它为什么这样做。我使用.NET Image类和我在此论坛上的其他线程上找到的转换器将PNG转换为byte[]

1 个答案:

答案 0 :(得分:1)

你没有提供有关崩溃的任何细节,所以我只能推测它失败的原因。

转换器可能内存不足?

我通常做的不是从Image转换为byte [],而是使用位图和锁定位...

例如,

using (var bitmap = new Bitmap("path\\to\\file.png"))
{
    var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
    bitmap.UnlockBits(data);
}