recrownedgtk/RecrownedGTK/Graphics/TextureData.cs

75 lines
2.7 KiB
C#
Raw Normal View History

2020-02-20 09:17:39 +00:00
using System.Drawing;
using System.IO;
using OpenTK.Graphics.OpenGL;
2020-02-20 19:49:36 +00:00
using OpenTK.Graphics;
using System;
2020-02-20 09:17:39 +00:00
namespace RecrownedGTK.Graphics {
2020-02-20 19:49:36 +00:00
public class TextureData : IDisposable {
private bool disposed;
2020-02-20 09:17:39 +00:00
int handle;
public readonly int width, height;
2020-02-20 19:49:36 +00:00
public TextureWrapMode textureWrapModeWidth, textureWrapModeHeight;
public Color4 borderColor;
public TextureMinFilter textureMinFilter;
public TextureMagFilter textureMagFilter;
2020-02-20 09:17:39 +00:00
2020-02-20 19:49:36 +00:00
public TextureData(string path) {
int width;
int height;
byte[] textureData = LoadPNG(path, out width, out height);
2020-02-20 19:49:36 +00:00
GenerateTexture(textureData, width, height);
}
public TextureData(byte[] textureData, int width, int height) {
textureWrapModeHeight = TextureWrapMode.ClampToBorder;
textureWrapModeWidth = TextureWrapMode.ClampToBorder;
textureMinFilter = TextureMinFilter.LinearMipmapLinear;
textureMagFilter = TextureMagFilter.Linear;
this.width = width;
this.height = height;
2020-02-20 19:49:36 +00:00
GenerateTexture(textureData, width, height);
}
private byte[] LoadPNG(string path, out int width, out int height) {
byte[] textureData = null;
using (FileStream file = new FileStream(path, FileMode.Open)) {
using (Bitmap bitmap = new Bitmap(file)) {
ImageConverter converter = new ImageConverter();
textureData = (byte[]) converter.ConvertTo(bitmap, typeof(byte[]));
width = bitmap.Width;
height = bitmap.Height;
}
}
return textureData;
}
2020-02-20 19:49:36 +00:00
private void GenerateTexture(byte[] textureData, int width, int height) {
if (handle != 0) throw new InvalidOperationException("This texture data already holds a texture.");
handle = GL.GenTexture();
Use();
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, textureData);
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
}
internal void Use() {
GL.BindTexture(TextureTarget.Texture2D, handle);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
2020-02-20 19:49:36 +00:00
if (disposed) return;
if (disposing) {
}
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.DeleteTexture(handle);
disposed = true;
}
~TextureData() {
Dispose(false);
2020-02-20 09:17:39 +00:00
}
}
}