aboutsummaryrefslogtreecommitdiff
path: root/apps/openmb/renderer/Texture.cpp
blob: e551f86f0dfcc6fda503e9f2b26b8107ff792105 (plain)
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
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

#include "Texture.hpp"

#include <iostream>

namespace renderer {
Texture::Texture () : mID( 0 ) {}

Texture::~Texture () {
    if( mID )
        glDeleteTextures( 1, &mID );
}

bool Texture::loadFromFile ( const std::string& path, bool flip ) {
    stbi_set_flip_vertically_on_load( flip );
    int            w, h, channels;
    unsigned char* data = stbi_load( path.c_str(), &w, &h, &channels, 0 );
    if( !data ) {
        std::cerr << "Failed to load texture: " << path << std::endl;
        return false;
    }

    GLenum format = GL_RGB;
    if( channels == 1 )
        format = GL_RED;
    else if( channels == 3 )
        format = GL_RGB;
    else if( channels == 4 )
        format = GL_RGBA;

    glGenTextures( 1, &mID );
    glBindTexture( GL_TEXTURE_2D, mID );
    glTexImage2D( GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, data );
    glGenerateMipmap( GL_TEXTURE_2D );

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    stbi_image_free( data );
    glBindTexture( GL_TEXTURE_2D, 0 );
    return true;
}

void Texture::bind ( unsigned unit ) const {
    glActiveTexture( GL_TEXTURE0 + unit );
    glBindTexture( GL_TEXTURE_2D, mID );
}

}   // namespace renderer