0% found this document useful (0 votes)
101 views20 pages

Laboratorio #9 - OpenGL - Programacion Grafica 2024

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views20 pages

Laboratorio #9 - OpenGL - Programacion Grafica 2024

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Universidad Nacional de Ingeniería

Programa Académico de Ingeniería en Computación

Asignatura: Programación Gráfica


Elaborado por: Danny Chávez
Laboratorio #9: Agregando iluminación a un modelo en OpenGL.

Objetivo: Implementar el Modelo de Phong en Graficas de Computadoras para tener iluminación en una
escena desarrollador en OpenGL.
VAO.cpp

#include"VAO.h"

// Constructor that generates a VAO ID


VAO::VAO()
{
glGenVertexArrays(1, &ID);
}

// Links a VBO Attribute such as a position or color to the VAO


void VAO::LinkAttrib(VBO& VBO, GLuint layout, GLuint numComponents, GLenum type,
GLsizeiptr stride, void* offset)
{
VBO.Bind();
glVertexAttribPointer(layout, numComponents, type, GL_FALSE, stride, offset);
glEnableVertexAttribArray(layout);
VBO.Unbind();
}

// Binds the VAO


void VAO::Bind()
{
glBindVertexArray(ID);
}

// Unbinds the VAO


void VAO::Unbind()
{
glBindVertexArray(0);
}

// Deletes the VAO


void VAO::Delete()
{
glDeleteVertexArrays(1, &ID);
}

VAO.h

#ifndef VAO_CLASS_H
#define VAO_CLASS_H

#include<glad/glad.h>
#include"VBO.h"

class VAO
{
public:
// ID reference for the Vertex Array Object
GLuint ID;
// Constructor that generates a VAO ID
VAO();

// Links a VBO Attribute such as a position or color to the VAO


void LinkAttrib(VBO& VBO, GLuint layout, GLuint numComponents, GLenum type,
GLsizeiptr stride, void* offset);
// Binds the VAO
void Bind();
// Unbinds the VAO
void Unbind();
// Deletes the VAO
void Delete();
};

#endif

light.vert

#version 330 core

layout (location = 0) in vec3 aPos;

uniform mat4 model;


uniform mat4 camMatrix;

void main()
{
gl_Position = camMatrix * model * vec4(aPos, 1.0f);
}

light.frag

#version 330 core

out vec4 FragColor;

uniform vec4 lightColor;

void main()
{
FragColor = lightColor;
}

default.vert

#version 330 core

// Positions/Coordinates
layout (location = 0) in vec3 aPos;
// Colors
layout (location = 1) in vec3 aColor;
// Texture Coordinates
layout (location = 2) in vec2 aTex;
// Normals (not necessarily normalized)
layout (location = 3) in vec3 aNormal;

// Outputs the color for the Fragment Shader


out vec3 color;
// Outputs the texture coordinates to the Fragment Shader
out vec2 texCoord;
// Outputs the normal for the Fragment Shader
out vec3 Normal;
// Outputs the current position for the Fragment Shader
out vec3 crntPos;

// Imports the camera matrix from the main function


uniform mat4 camMatrix;
// Imports the model matrix from the main function
uniform mat4 model;

void main()
{
// calculates current position
crntPos = vec3(model * vec4(aPos, 1.0f));
// Outputs the positions/coordinates of all vertices
gl_Position = camMatrix * vec4(crntPos, 1.0);

// Assigns the colors from the Vertex Data to "color"


color = aColor;
// Assigns the texture coordinates from the Vertex Data to "texCoord"
texCoord = aTex;
// Assigns the normal from the Vertex Data to "Normal"
Normal = aNormal;
}

default.frag

#version 330 core

// Outputs colors in RGBA


out vec4 FragColor;

// Imports the color from the Vertex Shader


in vec3 color;
// Imports the texture coordinates from the Vertex Shader
in vec2 texCoord;
// Imports the normal from the Vertex Shader
in vec3 Normal;
// Imports the current position from the Vertex Shader
in vec3 crntPos;

// Gets the Texture Unit from the main function


uniform sampler2D tex0;
// Gets the color of the light from the main function
uniform vec4 lightColor;
// Gets the position of the light from the main function
uniform vec3 lightPos;
// Gets the position of the camera from the main function
uniform vec3 camPos;

void main()
{
// ambient lighting
float ambient = 0.6f;

// diffuse lighting
vec3 normal = normalize(Normal);
vec3 lightDirection = normalize(lightPos - crntPos);
float diffuse = max(dot(normal, lightDirection), 0.0f);

// specular lighting
float specularLight = 1.50f;
vec3 viewDirection = normalize(camPos - crntPos);
vec3 reflectionDirection = reflect(-lightDirection, normal);
float specAmount = pow(max(dot(viewDirection, reflectionDirection), 0.0f), 5);
float specular = specAmount * specularLight;

// outputs final color


FragColor = texture(tex0, texCoord) * lightColor * (diffuse + ambient + specular);
}

VBO.cpp

#include"VBO.h"

// Constructor that generates a Vertex Buffer Object and links it to vertices


VBO::VBO(GLfloat* vertices, GLsizeiptr size)
{
glGenBuffers(1, &ID);
glBindBuffer(GL_ARRAY_BUFFER, ID);
glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW);
}

// Binds the VBO


void VBO::Bind()
{
glBindBuffer(GL_ARRAY_BUFFER, ID);
}

// Unbinds the VBO


void VBO::Unbind()
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

// Deletes the VBO


void VBO::Delete()
{
glDeleteBuffers(1, &ID);
}

VBO.h

#ifndef VBO_CLASS_H
#define VBO_CLASS_H

#include<glad/glad.h>

class VBO
{
public:
// Reference ID of the Vertex Buffer Object
GLuint ID;
// Constructor that generates a Vertex Buffer Object and links it to vertices
VBO(GLfloat* vertices, GLsizeiptr size);

// Binds the VBO


void Bind();
// Unbinds the VBO
void Unbind();
// Deletes the VBO
void Delete();
};

#endif

Camera.cpp

#include"Camara.h"

Camera::Camera(int width, int height, glm::vec3 position)


{
Camera::width = width;
Camera::height = height;
Position = position;
}

void Camera::updateMatrix(float FOVdeg, float nearPlane, float farPlane)


{
// Initializes matrices since otherwise they will be the null matrix
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);

// Makes camera look in the right direction from the right position
view = glm::lookAt(Position, Position + Orientation, Up);
// Adds perspective to the scene
projection = glm::perspective(glm::radians(FOVdeg), (float)width / height,
nearPlane, farPlane);

// Sets new camera matrix


cameraMatrix = projection * view;
}

void Camera::Matrix(Shader& shader, const char* uniform)


{
// Exports camera matrix
glUniformMatrix4fv(glGetUniformLocation(shader.ID, uniform), 1, GL_FALSE,
glm::value_ptr(cameraMatrix));
}

void Camera::Inputs(GLFWwindow* window)


{
// Handles key inputs
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
Position += speed * Orientation;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
Position += speed * -glm::normalize(glm::cross(Orientation, Up));
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
Position += speed * -Orientation;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
Position += speed * glm::normalize(glm::cross(Orientation, Up));
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
{
Position += speed * Up;
}
if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS)
{
Position += speed * -Up;
}
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
{
speed = 0.4f;
}
else if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_RELEASE)
{
speed = 0.1f;
}

// Handles mouse inputs


if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
// Hides mouse cursor
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

// Prevents camera from jumping on the first click


if (firstClick)
{
glfwSetCursorPos(window, (width / 2), (height / 2));
firstClick = false;
}

// Stores the coordinates of the cursor


double mouseX;
double mouseY;
// Fetches the coordinates of the cursor
glfwGetCursorPos(window, &mouseX, &mouseY);

// Normalizes and shifts the coordinates of the cursor such that they begin
in the middle of the screen
// and then "transforms" them into degrees
float rotX = sensitivity * (float)(mouseY - (height / 2)) / height;
float rotY = sensitivity * (float)(mouseX - (width / 2)) / width;

// Calculates upcoming vertical change in the Orientation


glm::vec3 newOrientation = glm::rotate(Orientation, glm::radians(-rotX),
glm::normalize(glm::cross(Orientation, Up)));
// Decides whether or not the next vertical Orientation is legal or not
if (abs(glm::angle(newOrientation, Up) - glm::radians(90.0f)) <=
glm::radians(85.0f))
{
Orientation = newOrientation;
}

// Rotates the Orientation left and right


Orientation = glm::rotate(Orientation, glm::radians(-rotY), Up);

// Sets mouse cursor to the middle of the screen so that it doesn't end up
roaming around
glfwSetCursorPos(window, (width / 2), (height / 2));
}
else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE)
{
// Unhides cursor since camera is not looking around anymore
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// Makes sure the next time the camera looks around it doesn't jump
firstClick = true;
}
}

Camara.h

#ifndef CAMERA_CLASS_H
#define CAMERA_CLASS_H

#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include<glm/gtx/rotate_vector.hpp>
#include<glm/gtx/vector_angle.hpp>

#include"shaderClass.h"

class Camera
{
public:
// Stores the main vectors of the camera
glm::vec3 Position;
glm::vec3 Orientation = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 Up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::mat4 cameraMatrix = glm::mat4(1.0f);

// Prevents the camera from jumping around when first clicking left click
bool firstClick = true;

// Stores the width and height of the window


int width;
int height;

// Adjust the speed of the camera and it's sensitivity when looking around
float speed = 0.1f;
float sensitivity = 100.0f;
// Camera constructor to set up initial values
Camera(int width, int height, glm::vec3 position);

// Updates the camera matrix to the Vertex Shader


void updateMatrix(float FOVdeg, float nearPlane, float farPlane);
// Exports the camera matrix to a shader
void Matrix(Shader& shader, const char* uniform);
// Handles camera inputs
void Inputs(GLFWwindow* window);
};
#endif

EBO.h

#ifndef EBO_CLASS_H
#define EBO_CLASS_H

#include<glad/glad.h>

class EBO
{
public:
// ID reference of Elements Buffer Object
GLuint ID;
// Constructor that generates a Elements Buffer Object and links it to indices
EBO(GLuint* indices, GLsizeiptr size);

// Binds the EBO


void Bind();
// Unbinds the EBO
void Unbind();
// Deletes the EBO
void Delete();
};

#endif

stb.cpp

#define STB_IMAGE_IMPLEMENTATION
#include<stb/stb_image.h>

Texture.cpp

#include"Texture.h"

Texture::Texture(const char* image, GLenum texType, GLenum slot, GLenum format, GLenum
pixelType)
{
// Assigns the type of the texture ot the texture object
type = texType;

// Stores the width, height, and the number of color channels of the image
int widthImg, heightImg, numColCh;
// Flips the image so it appears right side up
stbi_set_flip_vertically_on_load(true);
// Reads the image from a file and stores it in bytes
unsigned char* bytes = stbi_load(image, &widthImg, &heightImg, &numColCh, 0);
// Generates an OpenGL texture object
glGenTextures(1, &ID);
// Assigns the texture to a Texture Unit
glActiveTexture(slot);
glBindTexture(texType, ID);

// Configures the type of algorithm that is used to make the image smaller or
bigger
glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

// Configures the way the texture repeats (if it does at all)


glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_REPEAT);

// Extra lines in case you choose to use GL_CLAMP_TO_BORDER


// float flatColor[] = {1.0f, 1.0f, 1.0f, 1.0f};
// glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, flatColor);

// Assigns the image to the OpenGL Texture object


glTexImage2D(texType, 0, GL_RGBA, widthImg, heightImg, 0, format, pixelType,
bytes);
// Generates MipMaps
glGenerateMipmap(texType);

// Deletes the image data as it is already in the OpenGL Texture object


stbi_image_free(bytes);

// Unbinds the OpenGL Texture object so that it can't accidentally be modified


glBindTexture(texType, 0);
}

void Texture::texUnit(Shader& shader, const char* uniform, GLuint unit)


{
// Gets the location of the uniform
GLuint texUni = glGetUniformLocation(shader.ID, uniform);
// Shader needs to be activated before changing the value of a uniform
shader.Activate();
// Sets the value of the uniform
glUniform1i(texUni, unit);
}

void Texture::Bind()
{
glBindTexture(type, ID);
}

void Texture::Unbind()
{
glBindTexture(type, 0);
}

void Texture::Delete()
{
glDeleteTextures(1, &ID);
}
Main.cpp

#include<iostream>
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include<stb/stb_image.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>

#include"Texture.h"
#include"shaderClass.h"
#include"VAO.h"
#include"VBO.h"
#include"EBO.h"
#include"Camara.h"

const unsigned int width = 800;


const unsigned int height = 800;

//Coordenadas de Vertices

GLfloat vertices[] =
{ // COORDINATES / COLORS / TexCoord / NORMALS //
-0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f,
// Bottom side
-0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 5.0f, 0.0f, -1.0f, 0.0f,
// Bottom side
0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 5.0f, 0.0f, -1.0f, 0.0f,
// Bottom side
0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 0.0f, 0.0f, -1.0f, 0.0f,
// Bottom side

-0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 0.0f, -0.8f, 0.5f, 0.0f,
// Left Side
-0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 0.0f, -0.8f, 0.5f, 0.0f,
// Left Side
0.0f, 0.8f, 0.0f, 0.92f, 0.86f, 0.76f, 2.5f, 5.0f, -0.8f, 0.5f, 0.0f,
// Left Side

-0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 0.0f, 0.0f, 0.5f, -0.8f,
// Non-facing side
0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 0.0f, 0.0f, 0.5f, -0.8f,
// Non-facing side
0.0f, 0.8f, 0.0f, 0.92f, 0.86f, 0.76f, 2.5f, 5.0f, 0.0f, 0.5f, -0.8f,
// Non-facing side

0.5f, 0.0f, -0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 0.0f, 0.8f, 0.5f, 0.0f,
// Right side
0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 0.0f, 0.8f, 0.5f, 0.0f,
// Right side
0.0f, 0.8f, 0.0f, 0.92f, 0.86f, 0.76f, 2.5f, 5.0f, 0.8f, 0.5f, 0.0f,
// Right side
0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 5.0f, 0.0f, 0.0f, 0.5f, 0.8f,
// Facing side
-0.5f, 0.0f, 0.5f, 0.83f, 0.70f, 0.44f, 0.0f, 0.0f, 0.0f, 0.5f, 0.8f,
// Facing side
0.0f, 0.8f, 0.0f, 0.92f, 0.86f, 0.76f, 2.5f, 5.0f, 0.0f, 0.5f, 0.8f
// Facing side
};

// Indices for vertices order


GLuint indices[] =
{
0, 1, 2, // Bottom side
0, 2, 3, // Bottom side
4, 6, 5, // Left side
7, 9, 8, // Non-facing side
10, 12, 11, // Right side
13, 15, 14 // Facing side
};

GLfloat lightVertices[] =
{
-0.1f, -0.1f, 0.1f,
-0.1f, -0.1f, -0.1f,
0.1f, -0.1f, -0.1f,
0.1f, -0.1f, 0.1f,
-0.1f, 0.1f, 0.1f,
-0.1f, 0.1f, -0.1f,
0.1f, 0.1f, -0.1f,
0.1f, 0.1f, 0.1f
};

GLuint lightIndices[] =
{
0, 1, 2,
0, 2, 3,
0, 4, 7,
0, 7, 3,
3, 7, 6,
3, 6, 2,
2, 6, 5,
2, 5, 1,
1, 5, 4,
1, 4, 0,
4, 5, 6,
4, 6, 7
};

int main()
{
// Initialize GLFW
glfwInit();

// Tell GLFW what version of OpenGL we are using


// In this case we are using OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Tell GLFW we are using the CORE profile
// So that means we only have the modern functions
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

// Create a GLFWwindow object of 800 by 800 pixels


GLFWwindow* window = glfwCreateWindow(width, height, "Incorporando la funcionalidad
de la Camara en OpenGL", NULL, NULL);
// Error check if the window fails to create
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
// Introduce the window into the current context
glfwMakeContextCurrent(window);

//Load GLAD so it configures OpenGL


gladLoadGL();

// Specify the viewport of OpenGL in the Window


// In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
glViewport(0, 0, width, height);

// Generates Shader object using shaders defualt.vert and default.frag


Shader shaderProgram("default.vert", "default.frag");

// Generates Vertex Array Object and binds it


VAO VAO1;
VAO1.Bind();

// Generates Vertex Buffer Object and links it to vertices


VBO VBO1(vertices, sizeof(vertices));
// Generates Element Buffer Object and links it to indices
EBO EBO1(indices, sizeof(indices));

// Links VBO attributes such as coordinates and colors to VAO


VAO1.LinkAttrib(VBO1, 0, 3, GL_FLOAT, 11 * sizeof(float), (void*)0);
VAO1.LinkAttrib(VBO1, 1, 3, GL_FLOAT, 11 * sizeof(float), (void*)(3 *
sizeof(float)));
VAO1.LinkAttrib(VBO1, 2, 2, GL_FLOAT, 11 * sizeof(float), (void*)(6 *
sizeof(float)));
VAO1.LinkAttrib(VBO1, 3, 3, GL_FLOAT, 11 * sizeof(float), (void*)(8 *
sizeof(float)));

// Unbind all to prevent accidentally modifying them


VAO1.Unbind();
VBO1.Unbind();
EBO1.Unbind();

Shader lightShader("light.vert", "light.frag");


VAO lightVAO;
lightVAO.Bind();

VBO lightVBO(lightVertices, sizeof(lightVertices));


EBO lightEBO(lightIndices, sizeof(lightIndices));
lightVAO.LinkAttrib(lightVBO, 0, 3, GL_FLOAT, 3 * sizeof(float), (void*)0);

lightVAO.Unbind();
lightVBO.Unbind();
lightEBO.Unbind();

glm::vec4 lightColor = glm::vec4(1.0f, 0.0f, 0.0f, 0.0f);

glm::vec3 lightPos = glm::vec3(-0.1f, 0.2f, 0.0f);


glm::mat4 lightModel = glm::mat4(1.0f);
lightModel = glm::translate(lightModel, lightPos);

glm::vec3 pyramidPos = glm::vec3(0.5f, 0.0f, 0.0f);


glm::mat4 pyramidModel = glm::mat4(1.0f);
pyramidModel = glm::translate(pyramidModel, pyramidPos);

lightShader.Activate();
glUniformMatrix4fv(glGetUniformLocation(lightShader.ID, "model"), 1, GL_FALSE,
glm::value_ptr(lightModel));
glUniform4f(glGetUniformLocation(lightShader.ID, "lightColor"), lightColor.x,
lightColor.y, lightColor.z, lightColor.w);
shaderProgram.Activate();
glUniformMatrix4fv(glGetUniformLocation(shaderProgram.ID, "model"), 1, GL_FALSE,
glm::value_ptr(pyramidModel));
glUniform4f(glGetUniformLocation(shaderProgram.ID, "lightColor"), lightColor.x,
lightColor.y, lightColor.z, lightColor.w);
glUniform3f(glGetUniformLocation(shaderProgram.ID, "light"), lightPos.x, lightPos.y,
lightPos.z);

//Gets ID of uniform called "scale"


//GLuint uniID = glGetUniformLocation(shaderProgram.ID, "scale");

//Texture

int widthImg, heightImg, numColCh;


stbi_set_flip_vertically_on_load(true);
unsigned char* bytes = stbi_load("dog.jpg", &widthImg, &heightImg, &numColCh, 0);

//Texture dog("dog.png", GL_TEXTURE_2D, GL_TEXTURE0, GL_RGBA, GL_UNSIGNED_BYTE);


//dog.texUnit(shaderProgram, "tex0", 0);

GLuint texture;
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

//Para ubicar la textura


glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, widthImg, heightImg, 0, GL_RGB,
GL_UNSIGNED_BYTE, bytes);

//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE,


data);
glGenerateMipmap(GL_TEXTURE_2D);

//stbi_image_free(bytes);
glBindTexture(GL_TEXTURE_2D, 0);

GLuint tex0Uni = glGetUniformLocation(shaderProgram.ID, "tex0");


shaderProgram.Activate();
glUniform1i(tex0Uni, 0);

//Variables para controlar la rotacion


//float rotation = 0.0f;
//double prevTime = glfwGetTime();

glEnable(GL_DEPTH_TEST);

Camera camera(width, height, glm::vec3(0.0f, 0.0f, 2.0f));

// Main while loop


while (!glfwWindowShouldClose(window))
{
// Specify the color of the background
glClearColor(0.07f, 0.13f, 0.17f, 1.0f);

// Clean the back buffer and assign the new color to it


glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//Manejo de los valores ingresados en la camara


camera.Inputs(window);

//Actualiza y exporta la matriz de la camara al vertex shader


camera.updateMatrix(45.0f, 0.1f, 100.0f);

// Tell OpenGL which Shader Program we want to use


shaderProgram.Activate();
glUniform3f(glGetUniformLocation(shaderProgram.ID, "camPos"),
camera.Position.x, camera.Position.y, camera.Position.z);

camera.Matrix(shaderProgram, "camMatrix");

//Control de la Rotation de la Piramide con la textura incorporada por medio


de la funcion del tiempo.
//double crntTime = glfwGetTime();
//if (crntTime - prevTime >= 1/60)
//{

//rotation += 0.5f;
//prevTime = crntTime;

//}
//Inicializacion de las matrices para ser utilizadas
//glm::mat4 model = glm::mat4(1.0f);
//glm::mat4 view = glm::mat4(1.0f);
//glm::mat4 proj = glm::mat4(1.0f);

//Asignamos diferentes transformaciones a las matrices que tenemos


previamente declaradas
//Para controlar la rotacion de la piramide
//model = glm::rotate(model, glm::radians(rotation), glm::vec3(0.0f, 1.0f,
0.0f));

//Para establecer la matriz de traslacion


//view = glm::translate(view, glm::vec3(0.0f, -0.5f, -2.0f));

//Para establecer la proyeccion en perspectiva


//proj = glm::perspective(glm::radians(45.05f), (float)(width / height), 0.1f,
100.0f);//Posicion de la Camara

//Entradas de las matrices para ser usadas en el Vertex Shader


//int modelLoc = glGetUniformLocation(shaderProgram.ID, "model");
//glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

//int viewLoc = glGetUniformLocation(shaderProgram.ID, "view");


//glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

//int projLoc = glGetUniformLocation(shaderProgram.ID, "proj");


//glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));

// Assigns a value to the uniform


shaderProgram.Activate();

//Assigns a value to the uniform


//glUniform1f(uniID, 0.5f);
glBindTexture(GL_TEXTURE_2D, texture);

// Bind the VAO so OpenGL knows to use it


VAO1.Bind();

// Draw primitives, number of indices, datatype of indices, index of indices


glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(int), GL_UNSIGNED_INT,
0);

lightShader.Activate();
camera.Matrix(lightShader, "camMatrix");
lightVAO.Bind();
glDrawElements(GL_TRIANGLES, sizeof(lightIndices) / sizeof(int),
GL_UNSIGNED_INT, 0);

// Swap the back buffer with the front buffer


glfwSwapBuffers(window);
// Take care of all GLFW events
glfwPollEvents();
}

// Delete all the objects we've created


VAO1.Delete();
VBO1.Delete();
EBO1.Delete();
glDeleteTextures(1, &texture);
shaderProgram.Delete();
// Delete window before ending the program
glfwDestroyWindow(window);
// Terminate GLFW before ending the program
glfwTerminate();
return 0;
}

Texture.h

#ifndef TEXTURE_CLASS_H
#define TEXTURE_CLASS_H

#include<glad/glad.h>
#include<stb/stb_image.h>

#include"shaderClass.h"

class Texture
{
public:
GLuint ID;
GLenum type;
Texture(const char* image, GLenum texType, GLenum slot, GLenum format, GLenum
pixelType);

// Assigns a texture unit to a texture


void texUnit(Shader& shader, const char* uniform, GLuint unit);
// Binds a texture
void Bind();
// Unbinds a texture
void Unbind();
// Deletes a texture
void Delete();
};
#endif

EBO.cpp

#include"EBO.h"

// Constructor that generates a Elements Buffer Object and links it to indices


EBO::EBO(GLuint* indices, GLsizeiptr size)
{
glGenBuffers(1, &ID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, indices, GL_STATIC_DRAW);
}

// Binds the EBO


void EBO::Bind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ID);
}
// Unbinds the EBO
void EBO::Unbind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

// Deletes the EBO


void EBO::Delete()
{
glDeleteBuffers(1, &ID);
}

shaderClass.cpp

#include"shaderClass.h"

std::string get_file_contents(const char* filename)


{
std::ifstream in(filename, std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);

}
throw(errno);
}

//Procedemos a contruir el constructor de sombras

Shader::Shader(const char* vertexFile, const char* fragmentFile)


{
std::string vertexCode = get_file_contents(vertexFile);
std::string fragmentCode = get_file_contents(fragmentFile);

const char* vertexSource = vertexCode.c_str();


const char* fragmentSource = fragmentCode.c_str();

//Create Vertex Shader Object and get its reference


GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);

//Attach Vertex Shader source to the Vertex Shader Object


glShaderSource(vertexShader, 1, &vertexSource, NULL);

//Compile the Vertex Shader into machine code


glCompileShader(vertexShader);

//Create Fragment Shader Object and get its reference


GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

//Attach Fragment Shader source to the Fragment Shader Object


glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
//Compile the Vertex Shader into machine code
glCompileShader(fragmentShader);

//Create Shader Program Object and get its reference


ID = glCreateProgram();

//Attach the Vertex and Fragment Shaders to the Shader Program


glAttachShader(ID, vertexShader);
glAttachShader(ID, fragmentShader);

//Link all the shaders together into the Shader Program


glLinkProgram(ID);

//Delete the now useless Vertex and Fragment Shader Objects


glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}

void Shader::Activate()
{
glUseProgram(ID);
}

void Shader::Delete()
{
glUseProgram(ID);
}

shaderClass

#ifndef SHADER_CLASS_H
#define SHADER_CLASS_H

#include<glad/glad.h>
#include<iostream>
#include<fstream>
#include<sstream>
#include<iostream>
#include<cerrno>

std::string get_file_contents(const char* filename);

class Shader {

public:
GLuint ID;
Shader(const char* vertexFile, const char* fragmentFile);

void Activate();
void Delete();
};

#endif
RESULTADO DE LA EJECUCION

NOTA: Recuerde sustituir la textura de su polígono colocando la que usted considere para su diseño.

You might also like