2ae4155f6b9d800b3c67c44fbba325fc192184fb
[tar-legacy.git] / MCDV / Texture.hpp
1 #pragma once
2 #include <string>
3 #include <iostream>
4 #include <string>
5
6 #include <glad\glad.h>
7 #include <GLFW\glfw3.h>
8
9 #define STB_IMAGE_IMPLEMENTATION
10 #include "stb_image.h"
11
12 class Texture
13 {
14 public:
15 unsigned int texture_id;
16 Texture(std::string filepath);
17
18 void bind();
19
20 ~Texture();
21 };
22
23
24
25 bool USE_DEBUG2 = false;
26
27
28 Texture::Texture(std::string filepath)
29 {
30 //stbi_set_flip_vertically_on_load(true);
31
32 glGenTextures(1, &this->texture_id);
33
34 //Load texture using stb_image
35 int width, height, nrChannels;
36 unsigned char* data = stbi_load(filepath.c_str(), &width, &height, &nrChannels, 0);
37 if (data)
38 {
39 GLenum format;
40 if (nrChannels == 1)
41 format = GL_RED;
42 else if (nrChannels == 3)
43 format = GL_RGB;
44 else if (nrChannels == 4)
45 format = GL_RGBA;
46
47 glBindTexture(GL_TEXTURE_2D, this->texture_id);
48 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, GL_UNSIGNED_BYTE, data);
49 glGenerateMipmap(GL_TEXTURE_2D);
50
51 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
52 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
53 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
54 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
55
56 stbi_image_free(data);
57
58 if (USE_DEBUG2)
59 {
60 std::cout << "Texture loaded, info:" << std::endl;
61 std::cout << filepath << std::endl;
62 std::cout << "width: " << width << std::endl;
63 std::cout << "height: " << height << std::endl;
64 }
65 else
66 {
67 std::cout << "Loading texture: " << filepath << std::endl;
68 }
69 }
70 else
71 {
72 std::cout << "ERROR::IMAGE::LOAD_FAILED" << std::endl;
73 }
74 }
75
76 Texture::~Texture()
77 {
78 }
79
80 void Texture::bind()
81 {
82 glBindTexture(GL_TEXTURE_2D, this->texture_id);
83 }