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