Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created September 26, 2016 20:32
Show Gist options
  • Save matthewjberger/fae7b1ac293d927e4d862b46652ccef5 to your computer and use it in GitHub Desktop.
Save matthewjberger/fae7b1ac293d927e4d862b46652ccef5 to your computer and use it in GitHub Desktop.
#include <MainState.h>
#include "ShaderProgram.h"
/* Created by following the example from the excellent OpenGL Superbible 7 book */
GLuint MainState::compile_shaders()
{
ShaderProgram program;
// Source code for vertex shader
const std::string vertex_shader_source = R"(
#version 330 core
layout(location = 0) in vec4 offset;
void main(void)
{
const vec4 vertices[3] =
vec4[3](vec4(0.25, -0.25, 0.5, 1.0),
vec4(-0.25, -0.25, 0.5, 1.0),
vec4(0.25, 0.25, 0.5, 1.0));
gl_Position = vertices[gl_VertexID] + offset;
}
)";
// Source code for fragment shader
const std::string fragment_shader_source = R"(
#version 330 core
out vec4 color;
void main(void)
{
color = vec4(0.0, 0.8, 1.0, 1.0);
}
)";
program.add_shader_from_source(vertex_shader_source, GL_VERTEX_SHADER);
program.add_shader_from_source(vertex_shader_source, GL_FRAGMENT_SHADER);
// Create program, attach shaders, and link the shaders
program.create_program();
program.link_program();
return program.id();
}
void MainState::initialize()
{
// Create our shader program
rendering_program = compile_shaders();
// Create a dummy VAO
glGenVertexArrays(1, &vertex_array_object);
glBindVertexArray(vertex_array_object);
}
void MainState::finalize()
{
// Delete our dummy VAO and our shader program
glDeleteVertexArrays(1, &vertex_array_object);
glDeleteProgram(rendering_program);
}
void MainState::handle_events(SDL_Event event) {}
void MainState::update() {}
void MainState::draw()
{
// Get the current time
double currentTime = SDL_GetTicks() / 1000.00;
// Create a color that varies gradually and cyclically with time
const GLfloat color[] = { (float)sin(currentTime) * 0.5f + 0.5f,
(float)cos(currentTime) * 0.5f + 0.5f,
0.0f, 1.0f };
// Clear the screen to the color above
glClearBufferfv(GL_COLOR, 0, color);
// Use the shader program we created earlier
glUseProgram(rendering_program);
// Create an array of four floats that move a point in a circle in x,y over time
GLfloat attrib[] = {
(float)sin(currentTime) * 0.5f,
(float)cos(currentTime) * 0.6f,
0.0f, 0.0f };
// Update the 'offset' vertex attribute with the value above
glVertexAttrib4fv(0, attrib);
// Process three vertices as a triangle
glDrawArrays(GL_TRIANGLES, 0, 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment