Reflection
[opengl.git] / skybox.cpp
1 #include "shapes.hpp"
2 #include "skybox.hpp"
3 #include "image.hpp"
4 #include <glm/gtc/type_ptr.hpp>
5         
6 Skybox::Skybox(const std::vector<std::string> faces): program("skyboxvert.glsl", "skyboxfrag.glsl") {
7         glGenTextures(1, &texId);
8         glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
9         glDepthFunc(GL_LEQUAL);
10
11         int width, height, numChans;
12         for (int i = 0; i < faces.size(); i++) {
13                 Image img(faces[i]);
14
15                 glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.data());
16         }
17
18         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
19         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
20         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
21         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
22         glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
23
24         glGenVertexArrays(1, &vao);
25         glBindVertexArray(vao);
26
27         GLuint vbo;
28         glGenBuffers(1, &vbo);
29
30         auto vertices = cube();
31
32         //reverse so facing inside out
33         std::reverse(vertices.begin(), vertices.end());
34
35         glBindBuffer(GL_ARRAY_BUFFER, vbo);
36         glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
37         
38         GLuint posLoc = glGetAttribLocation(program.progId, "pos");
39         glEnableVertexAttribArray(posLoc);
40         glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
41 }
42
43 void Skybox::draw(glm::mat4 proj, glm::mat4 view) const {
44         glUseProgram(program.progId);
45
46         glBindVertexArray(vao);
47
48         GLuint projLoc = glGetUniformLocation(program.progId, "projection");
49         glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
50
51         GLuint viewLoc = glGetUniformLocation(program.progId, "view");
52         view = glm::mat4(glm::mat3(view));
53         glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
54
55         glActiveTexture(GL_TEXTURE0);
56         glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
57         glDrawArrays(GL_TRIANGLES, 0, 36);
58 }
59
60 GLuint Skybox::getTexture() const {
61         return texId;
62 }