-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTexture.cs
76 lines (65 loc) · 2.81 KB
/
Texture.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using Silk.NET.OpenGL;
using System;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Processing;
namespace Abstractions
{
public class Texture : IDisposable
{
private uint _handle;
private GL _gl;
public unsafe Texture(GL gl, string path, FlipMode fm)
{
//Loading an image using imagesharp.
Image<Rgba32> img = (Image<Rgba32>)Image.Load(path);
//We need to flip our image as image sharps coordinates has origin (0, 0) in the top-left corner,
//where as openGL has origin in the bottom-left corner.
img.Mutate(x => x.Flip(fm));
fixed (void* data = &MemoryMarshal.GetReference(img.GetPixelRowSpan(0)))
{
//Loading the actual image.
Load(gl, data, (uint)img.Width, (uint)img.Height);
}
//Deleting the img from imagesharp.
img.Dispose();
}
public unsafe Texture(GL gl, Span<byte> data, uint width, uint height)
{
//We want the ability to create a texture using data generated from code aswell.
fixed (void* d = &data[0])
{
Load(gl, d, width, height);
}
}
private unsafe void Load(GL gl, void* data, uint width, uint height)
{
//Saving the gl instance.
_gl = gl;
//Generating the opengl handle;
_handle = _gl.GenTexture();
Bind();
//Setting the data of a texture.
_gl.TexImage2D(TextureTarget.Texture2D, 0, (int)InternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, data);
//Setting some texture perameters so the texture behaves as expected.
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)GLEnum.Repeat);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)GLEnum.Repeat);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)GLEnum.Linear);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)GLEnum.Linear);
//Generating mipmaps.
_gl.GenerateMipmap(TextureTarget.Texture2D);
}
public void Bind(TextureUnit textureSlot = TextureUnit.Texture0)
{
//When we bind a texture we can choose which textureslot we can bind it to.
_gl.ActiveTexture(textureSlot);
_gl.BindTexture(TextureTarget.Texture2D, _handle);
}
public void Dispose()
{
//In order to dispose we need to delete the opengl handle for the texure.
_gl.DeleteTexture(_handle);
}
}
}