Bubba-3D  0.9.0
Awesome game engine!
Texture.cpp
1 /*
2  * This file is part of Bubba-3D.
3  *
4  * Bubba-3D is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * Bubba-3D is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public License
15  * along with Bubba-3D. If not, see http://www.gnu.org/licenses/.
16  */
17 #include "glutil/glutil.h"
18 #include <Logger.h>
19 #include <StdOutLogHandler.h>
20 #include "Texture.h"
21 
22 #define STB_IMAGE_IMPLEMENTATION
23 
24 #include "stb_image.h"
25 
26 
27 void Texture::bind(GLenum textureUnit){
28  glActiveTexture(textureUnit);
29  glBindTexture(GL_TEXTURE_2D, textureID);
30 }
31 
32 void Texture::loadTexture(std::string fileName)
33 {
34  stbi_set_flip_vertically_on_load(true);
35 
36  int comp;
37  unsigned char* image = stbi_load(fileName.c_str(), &width, &height, &comp, 0);
38 
39  if(image == nullptr) {
40  Logger::logError("Couldnt load image "+ fileName);
41  }
42 
43  GLuint texid;
44  glGenTextures(1, &texid);
45  glActiveTexture(GL_TEXTURE0);
46  CHECK_GL_ERROR();
47  glBindTexture(GL_TEXTURE_2D, texid);
48  CHECK_GL_ERROR();
49 
50 
51  GLenum format = comp == 3 ? GL_RGB : GL_RGBA;
52 
53  glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA_EXT,
54  width, height, 0, format, GL_UNSIGNED_BYTE, image);
55 
56  CHECK_GL_ERROR();
57  glGenerateMipmap(GL_TEXTURE_2D);
58  CHECK_GL_ERROR();
59  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
60  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
61  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
62  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
63  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16);
64  CHECK_GL_ERROR();
65 
66  glBindTexture(GL_TEXTURE_2D, 0);
67  CHECK_GL_ERROR();
68  textureID = texid;
69 
70  stbi_image_free(image);
71  Logger::logInfo("Loaded image: " + fileName);
72 }
73 
74 int Texture::getHeight() {
75  return height;
76 }
77 
78 int Texture::getWidth() {
79  return width;
80 }
81 
82 GLuint Texture::getID() {
83  return textureID;
84 };