1 /**
2 Copyright: Copyright (c) 2013-2016 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 
7 module anchovy.texture;
8 
9 import std.conv, std.file;
10 import std.stdio;
11 import std.string;
12 
13 import derelict.opengl3.gl3;
14 import dlib.image.image : SuperImage;
15 import anchovy.glerrors;
16 
17 //version = debugTexture;
18 
19 enum TextureTarget : uint
20 {
21 	target1d = GL_TEXTURE_1D,
22 	target2d = GL_TEXTURE_2D,
23 	target3d = GL_TEXTURE_3D,
24 	targetRectangle = GL_TEXTURE_RECTANGLE,
25 	targetBuffer = GL_TEXTURE_BUFFER,
26 	targetCubeMap = GL_TEXTURE_CUBE_MAP,
27 	target1dArray = GL_TEXTURE_1D_ARRAY,
28 	target2dArray = GL_TEXTURE_2D_ARRAY,
29 	targetCubeMapArray = GL_TEXTURE_CUBE_MAP_ARRAY,
30 	target2dMultisample = GL_TEXTURE_2D_MULTISAMPLE,
31 	target2dMultisampleArray = GL_TEXTURE_2D_MULTISAMPLE_ARRAY,
32 }
33 
34 enum TextureFormat : uint
35 {
36 	r = GL_RED,
37 	rg = GL_RG,
38 	rgb = GL_RGB,
39 	rgba = GL_RGBA,
40 }
41 
42 class Texture
43 {
44 private:
45 	TextureFormat texFormat;
46 	uint glTextureHandle;
47 	TextureTarget texTarget;
48 
49 public:
50 	this(SuperImage image, TextureTarget target, TextureFormat format)
51 	{
52 		texTarget = target;
53 		texFormat = format;
54 		checkgl!glGenTextures(1, &glTextureHandle);
55 		loadFromImage(image);
56 	}
57 
58 	void bind(uint textureUnit = 0)
59 	{
60 		checkgl!glBindTexture(texTarget, glTextureHandle);
61 	}
62 
63 	void unbind()
64 	{
65 		checkgl!glBindTexture(texTarget, 0);
66 	}
67 
68 	void loadFromImage(SuperImage img)
69 	{
70 		bind();
71 		checkgl!glTexImage2D(texTarget, 0, texFormat, img.width, img.height, 0, texFormat, GL_UNSIGNED_BYTE, img.data.ptr);
72 		checkgl!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
73 		checkgl!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
74 		unbind();
75 	}
76 
77 	void unload()
78 	{
79 		glDeleteTextures(1, &glTextureHandle);
80 	}
81 }