aboutsummaryrefslogtreecommitdiffstats
path: root/yage/base/imageloader.cpp
blob: 0d7d5df98bb44a037f1cc8ef22325bf8d1830d26 (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
54
55
56
57
/* ----------------------------------------------------------------------------
 * imageloader.cpp
 *
 * Copyright (c) 2017 Yann Herklotz Grave <ymherklotz@gmail.com> -- MIT License
 * See file LICENSE for more details
 * ----------------------------------------------------------------------------
 */

#include <yage/base/imageloader.h>
#include <yage/base/iomanager.h>
#include <yage/base/picopng.h>

#include <stdexcept>

namespace yage
{

Texture ImageLoader::loadPng(const std::string &file_path)
{
    std::vector<unsigned char> in;
    std::vector<unsigned char> out;
    unsigned long width, height;

    if (!IoManager::readFileToBuffer(file_path, in)) {
        throw std::runtime_error("Failed to load '" + file_path +
                                 "' to buffer");
    }

    int error_code = decodePNG(out, width, height, &in[0], in.size());
    if (error_code != 0) {
        throw std::runtime_error("Failed to load '" + file_path +
                                 "' to png with error code" +
                                 std::to_string(error_code));
    }

    Texture texture{0, (int)width, (int)height};

    glGenTextures(1, &texture.id);

    glBindTexture(GL_TEXTURE_2D, texture.id);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, &out[0]);

    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_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                    GL_LINEAR_MIPMAP_LINEAR);

    glGenerateMipmap(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, 0);

    return texture;
}

} // namespace yage