OpenGLBook.com sample - I'm not getting it to work!

Started by
10 comments, last by Paradoxia 12 years, 8 months ago
Hello fellows!

So, i've been updating my OpenGL knowledge and managed to get stuck. I've followed the guides over at OpenGLBook.com and all was going well, untill i hit Chapter 4.
The code i've written is next to identical to their sample code, yet their code works and mine doesn't. I have even copy pasted my code into theirs, replacing every function with mine, and that still works. But my code alone is not up to the task sadly. There must be something i'm missing. Please, help me out!

My code


/*
* Free Glut test.
*/
#include "utils.h"

/* === DEFINITIONS === */
#define WINDOW_TITLE "Chapter 4: 3D"
#define SHADER_PROGRAM 0
#define SHADER_FRAGMENT 1
#define SHADER_VERTEX 2
#define BUFFER_VAO 0
#define BUFFER_VBO 1
#define BUFFER_IBO 2

/* === GLOBAL VARIABLES === */
GLuint projMatUniLoc, viewMatUniLoc, modelMatUniLoc;
GLuint bufferIds[3] = {0}, shaderIds[3] = {0};
int windowWidth, windowHeight, windowHandle;
float cubeRotation;
clock_t lastTime;
unsigned frames;

/* === MATRIXES === */
Matrix projectionMatrix, viewMatrix, modelMatrix;

/* === FUNCTION PROTOTYPES === */
void init(int, char **);
void initWindow(int, char **);
void resize(int, int);
void render(void);
void timer(int);
void idle(void);
void createCube(void);
void destroyCube(void);
void drawCube(void);

/*
* main():
* Main entry point of the application.
*/
int main(int argc, char **argv) {
/* Initialize everything we need */
init(argc, argv);

/* Start the glut loop */
glutMainLoop();

exit(EXIT_SUCCESS);
}

/*
* init(argc, argv):
* Initializes everything we need to start running.
*/
void init(int argc, char **argv) {
GLenum ret;
/* Create our openGL window */
windowWidth = 1024;
windowHeight = 768;
initWindow(argc, argv);

/* Initialize glew */
ret = glewInit();
if (GLEW_OK != ret) {
fprintf(stderr, "ERROR: %s\n", glewGetErrorString(ret));
exit(EXIT_FAILURE);
}

/* Get the running openGL version */
fprintf(stdout, "INFO: OpenGL Version: %s\n", glGetString(GL_VERSION));

/* Empty potential errors */
glGetError();

/* Clear the screen */
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

/* Enable depth test */
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
ExitOnGLError("ERROR: Could not set OpenGL depth testing");

/* Enable culling of faces */
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
ExitOnGLError("Error: Could not set OpenGL culling");

/* Setup out default matrices */
modelMatrix = IDENTITY_MATRIX;
projectionMatrix = IDENTITY_MATRIX;
viewMatrix = IDENTITY_MATRIX;
TranslateMatrix(&viewMatrix, 0, 0, -2);

/* Create our initial cube */
createCube();
}

/*
* initWindow(argc, argv):
* Create the openGL window for us.
*/
void initWindow(int argc, char **argv) {
/* Initialize glut */
glutInit(&argc, argv);
glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
glutInitWindowSize(windowWidth, windowHeight);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

/* Create the window */
windowHandle = glutCreateWindow(WINDOW_TITLE);
if (windowHandle < 1) {
fprintf(stderr, "ERROR: Could not create window.\n");
exit(EXIT_FAILURE);
}

/* Set glut callback functions */
glutReshapeFunc(resize);
glutDisplayFunc(render);
glutIdleFunc(idle);
glutTimerFunc(0, timer, 0);
glutCloseFunc(destroyCube);
}

/*
* rezie(width, height):
* Resize the openGL window.
*/
void resize(int width, int height) {
/* Save dimensions */
windowWidth = width;
windowHeight = height;

/* Set viewport */
glViewport(0, 0, width, height);

/* Change our projection matrix */
projectionMatrix = CreateProjectionMatrix(60,
(float)windowWidth / windowHeight, 1.0f, 100.0f);
glUseProgram(shaderIds[0]);
glUniformMatrix4fv(projMatUniLoc, 1, GL_FALSE, projectionMatrix.m);
glUseProgram(0);
}

/*
* render()
* Render our openGL scene.
*/
void render(void) {
++frames;

/* Clear screen */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* Draw our cube */
drawCube();

/* Swap buffers and update display */
glutSwapBuffers();
glutPostRedisplay();
}

/*
* idle():
* Logic function.
*/
void idle(void) {
glutPostRedisplay();
}

/*
* timer(val):
* Timer to count FPS.
*/
void timer(int val) {
char fpsString[512];

if (val != 0) {
/* Allocate memory and copy string */
sprintf(fpsString, "%s: %d FPS @ %d x %d", WINDOW_TITLE,
frames * 4, windowWidth, windowHeight);

/* Set it as title */
glutSetWindowTitle(fpsString);
}

frames = 0;
glutTimerFunc(250, timer, 1);
}

/*
* createCube():
* Setup the cube.
*/
void createCube(void) {
const Vertex vertices[8] = {
{{-0.5f, -0.5f, 0.5f, 1}, {0, 0, 1, 1}},
{{-0.5f, 0.5f, 0.5f, 1}, {1, 0, 0, 1}},
{{0.5f, 0.5f, 0.5f, 1}, {0, 1, 0, 1}},
{{0.5f, -0.5f, 0.5f, 1}, {1, 1, 0, 1}},
{{-0.5f, -0.5f, -0.5f, 1}, {1, 1, 1, 1}},
{{-0.5f, 0.5f, -0.5f, 1}, {1, 0, 0, 1}},
{{0.5f, 0.5f, -0.5f, 1}, {1, 0, 1, 1}},
{{0.5f, -0.5f, -0.5f, 1}, {0, 0, 1, 1}}
};
const GLuint indices[36] = {
0, 2, 1, 0, 3, 2, 4, 3, 0, 4, 7, 3,
4, 1, 5, 4, 0, 1, 3, 6, 2, 3, 7, 6,
1, 6, 5, 1, 2, 6, 7, 5, 6, 7, 4, 5
};

/* Generate the shader program */
shaderIds[SHADER_PROGRAM] = glCreateProgram();
ExitOnGLError("ERROR: Could not create shader program");

/* Load and attach shaders */
shaderIds[SHADER_FRAGMENT] = LoadShader("fragment.glsl", GL_FRAGMENT_SHADER);
shaderIds[SHADER_VERTEX] = LoadShader("vertex.glsl", GL_VERTEX_SHADER);
glAttachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_FRAGMENT]);
glAttachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_VERTEX]);

/* Link shader program */
glLinkProgram(shaderIds[SHADER_PROGRAM]);
ExitOnGLError("ERROR: Could not link shader program");

/* Retrive shader uniforms */
modelMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "modelMatrix");
viewMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "viewMatrix");
projMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "projectionMatrix");
ExitOnGLError("ERROR: Could not get shader uniform locations");

/* Generate and bind our vertex array object */
glGenVertexArrays(1, &bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not generate VAO");
glBindVertexArray(bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not bind VAO");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
ExitOnGLError("ERROR: Could not enable vertex attributes");

/* Bind VBO and send data */
glGenBuffers(2, &bufferIds[BUFFER_VBO]);
glBindBuffer(GL_ARRAY_BUFFER, bufferIds[BUFFER_VBO]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind VBO to VAO");

/* Set the attributes for our VAO */
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (GLvoid *)0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertices[0]),
(GLvoid *)sizeof(vertices[0].Position));
ExitOnGLError("ERROR: Could not set VAO attributes");

/* Bind IBO and send data */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferIds[BUFFER_IBO]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind IBO to VAO");
glBindVertexArray(0);
}

/*
* destroyCube():
* Destroy out little cubie.
*/
void destroyCube(void) {
/* Detach and delete shaders */
glDetachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_FRAGMENT]);
glDetachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_VERTEX]);
glDeleteShader(shaderIds[SHADER_FRAGMENT]);
glDeleteShader(shaderIds[SHADER_VERTEX]);
glDeleteProgram(shaderIds[SHADER_PROGRAM]);
ExitOnGLError("ERROR: Could not destroy shaders");

/* Delete and destroy buffers */
glDeleteBuffers(2, &bufferIds[BUFFER_VBO]);
glDeleteVertexArrays(1, &bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not destroy buffer objects");
}

/*
* drawCube():
* Draw the cube.
*/
void drawCube(void) {
float cubeAngle;
clock_t now;

/* Current time */
now = clock();
if (lastTime == 0)
lastTime = now;

/* Adjust rotation */
cubeRotation += 45.0f * ((float)(now - lastTime) / CLOCKS_PER_SEC);
cubeAngle = DegreesToRadians(cubeRotation);
lastTime = now;

/* Rotate the matrix */
modelMatrix = IDENTITY_MATRIX;
RotateAboutY(&modelMatrix, cubeAngle);
RotateAboutX(&modelMatrix, cubeAngle);

/* Use the shader program so we can manipluate */
glUseProgram(shaderIds[SHADER_PROGRAM]);

/* Adjust matrix uniform locations */
glUniformMatrix4fv(modelMatUniLoc, 1, GL_FALSE, modelMatrix.m);
glUniformMatrix4fv(viewMatUniLoc, 1, GL_FALSE, viewMatrix.m);
ExitOnGLError("ERROR: Could not set the shader uniforms");

/* Bind and draw the VAO */
glBindVertexArray(bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not bind VAO for drawing");
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (GLvoid *)0);
ExitOnGLError("ERROR: Could not draw the cube");

/* Done manipulating */
glBindVertexArray(0);
glUseProgram(0);
}




Their code


/* Copyright (C) 2011 by Eddy Luten

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "Utils.h"
#define WINDOW_TITLE_PREFIX "Chapter 4"

int CurrentWidth = 800,
CurrentHeight = 600,
WindowHandle = 0;

unsigned FrameCount = 0;

GLuint
ProjectionMatrixUniformLocation,
ViewMatrixUniformLocation,
ModelMatrixUniformLocation,
BufferIds[3] = { 0 },
ShaderIds[3] = { 0 };

Matrix
ProjectionMatrix,
ViewMatrix,
ModelMatrix;

float CubeRotation = 0;
clock_t LastTime = 0;

void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void ResizeFunction(int, int);
void RenderFunction(void);
void TimerFunction(int);
void IdleFunction(void);
void CreateCube(void);
void DestroyCube(void);
void DrawCube(void);

int main(int argc, char* argv[])
{
Initialize(argc, argv);

glutMainLoop();

exit(EXIT_SUCCESS);
}

void Initialize(int argc, char* argv[])
{
GLenum GlewInitResult;

InitWindow(argc, argv);

glewExperimental = GL_TRUE;
GlewInitResult = glewInit();

if (GLEW_OK != GlewInitResult) {
fprintf(
stderr,
"ERROR: %s\n",
glewGetErrorString(GlewInitResult)
);
exit(EXIT_FAILURE);
}

fprintf(
stdout,
"INFO: OpenGL Version: %s\n",
glGetString(GL_VERSION)
);

glGetError();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
ExitOnGLError("ERROR: Could not set OpenGL depth testing options");

glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
ExitOnGLError("ERROR: Could not set OpenGL culling options");

ModelMatrix = IDENTITY_MATRIX;
ProjectionMatrix = IDENTITY_MATRIX;
ViewMatrix = IDENTITY_MATRIX;
TranslateMatrix(&ViewMatrix, 0, 0, -2);

CreateCube();
}

void InitWindow(int argc, char* argv[])
{
glutInit(&argc, argv);

glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);

glutSetOption(
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);

glutInitWindowSize(CurrentWidth, CurrentHeight);

glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);

if(WindowHandle < 1) {
fprintf(
stderr,
"ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}

glutReshapeFunc(ResizeFunction);
glutDisplayFunc(RenderFunction);
glutIdleFunc(IdleFunction);
glutTimerFunc(0, TimerFunction, 0);
glutCloseFunc(DestroyCube);
}

void ResizeFunction(int Width, int Height)
{
CurrentWidth = Width;
CurrentHeight = Height;
glViewport(0, 0, CurrentWidth, CurrentHeight);
ProjectionMatrix =
CreateProjectionMatrix(
60,
(float)CurrentWidth / CurrentHeight,
1.0f,
100.0f
);

glUseProgram(ShaderIds[0]);
glUniformMatrix4fv(ProjectionMatrixUniformLocation, 1, GL_FALSE, ProjectionMatrix.m);
glUseProgram(0);
}

void RenderFunction(void)
{
++FrameCount;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

DrawCube();

glutSwapBuffers();
glutPostRedisplay();
}

void IdleFunction(void)
{
glutPostRedisplay();
}

void TimerFunction(int Value)
{
if (0 != Value) {
char* TempString = (char*)
malloc(512 + strlen(WINDOW_TITLE_PREFIX));

sprintf(
TempString,
"%s: %d Frames Per Second @ %d x %d",
WINDOW_TITLE_PREFIX,
FrameCount * 4,
CurrentWidth,
CurrentHeight
);

glutSetWindowTitle(TempString);
free(TempString);
}

FrameCount = 0;
glutTimerFunc(250, TimerFunction, 1);
}

void CreateCube()
{
const Vertex VERTICES[8] =
{
{ { -.5f, -.5f, .5f, 1 }, { 0, 0, 1, 1 } },
{ { -.5f, .5f, .5f, 1 }, { 1, 0, 0, 1 } },
{ { .5f, .5f, .5f, 1 }, { 0, 1, 0, 1 } },
{ { .5f, -.5f, .5f, 1 }, { 1, 1, 0, 1 } },
{ { -.5f, -.5f, -.5f, 1 }, { 1, 1, 1, 1 } },
{ { -.5f, .5f, -.5f, 1 }, { 1, 0, 0, 1 } },
{ { .5f, .5f, -.5f, 1 }, { 1, 0, 1, 1 } },
{ { .5f, -.5f, -.5f, 1 }, { 0, 0, 1, 1 } }
};

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

ShaderIds[0] = glCreateProgram();
ExitOnGLError("ERROR: Could not create the shader program");
{
ShaderIds[1] = LoadShader("SimpleShader.fragment.glsl", GL_FRAGMENT_SHADER);
ShaderIds[2] = LoadShader("SimpleShader.vertex.glsl", GL_VERTEX_SHADER);
glAttachShader(ShaderIds[0], ShaderIds[1]);
glAttachShader(ShaderIds[0], ShaderIds[2]);
}
glLinkProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not link the shader program");

ModelMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ModelMatrix");
ViewMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ViewMatrix");
ProjectionMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ProjectionMatrix");
ExitOnGLError("ERROR: Could not get shader uniform locations");

glGenVertexArrays(1, &BufferIds[0]);
ExitOnGLError("ERROR: Could not generate the VAO");
glBindVertexArray(BufferIds[0]);
ExitOnGLError("ERROR: Could not bind the VAO");

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
ExitOnGLError("ERROR: Could not enable vertex attributes");

glGenBuffers(2, &BufferIds[1]);
ExitOnGLError("ERROR: Could not generate the buffer objects");

glBindBuffer(GL_ARRAY_BUFFER, BufferIds[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES), VERTICES, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind the VBO to the VAO");

glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VERTICES[0]), (GLvoid*)0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VERTICES[0]), (GLvoid*)sizeof(VERTICES[0].Position));
ExitOnGLError("ERROR: Could not set VAO attributes");

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferIds[2]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INDICES), INDICES, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind the IBO to the VAO");

glBindVertexArray(0);
}

void DestroyCube()
{
glDetachShader(ShaderIds[0], ShaderIds[1]);
glDetachShader(ShaderIds[0], ShaderIds[2]);
glDeleteShader(ShaderIds[1]);
glDeleteShader(ShaderIds[2]);
glDeleteProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not destroy the shaders");

glDeleteBuffers(2, &BufferIds[1]);
glDeleteVertexArrays(1, &BufferIds[0]);
ExitOnGLError("ERROR: Could not destroy the buffer objects");
}

void DrawCube(void)
{
float CubeAngle;
clock_t Now = clock();

if (LastTime == 0)
LastTime = Now;

CubeRotation += 45.0f * ((float)(Now - LastTime) / CLOCKS_PER_SEC);
CubeAngle = DegreesToRadians(CubeRotation);
LastTime = Now;

ModelMatrix = IDENTITY_MATRIX;
RotateAboutY(&ModelMatrix, CubeAngle);
RotateAboutX(&ModelMatrix, CubeAngle);

glUseProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not use the shader program");

glUniformMatrix4fv(ModelMatrixUniformLocation, 1, GL_FALSE, ModelMatrix.m);
glUniformMatrix4fv(ViewMatrixUniformLocation, 1, GL_FALSE, ViewMatrix.m);
ExitOnGLError("ERROR: Could not set the shader uniforms");

glBindVertexArray(BufferIds[0]);
ExitOnGLError("ERROR: Could not bind the VAO for drawing purposes");

glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (GLvoid*)0);
ExitOnGLError("ERROR: Could not draw the cube");

glBindVertexArray(0);
glUseProgram(0);
}
Omg, zombie! Zomgbie.
Advertisement
What is happening? What "won't work"? Compile error? Crash? Black Screen? Any debug info?
Hi Zomgbie,

What exactly doesn't work? You could provide some more specific information besides simply pasting the code from the samples:

Do you get any errors, black screens, can you tell me anything about the output? What platform are you on? What hardware are you using? Are you checking glGetError along the way?



The more info you can provide, the better.


Eddy


Hello fellows!

So, i've been updating my OpenGL knowledge and managed to get stuck. I've followed the guides over at OpenGLBook.com and all was going well, untill i hit Chapter 4.
The code i've written is next to identical to their sample code, yet their code works and mine doesn't. I have even copy pasted my code into theirs, replacing every function with mine, and that still works. But my code alone is not up to the task sadly. There must be something i'm missing. Please, help me out!

My code


/*
* Free Glut test.
*/
#include "utils.h"

/* === DEFINITIONS === */
#define WINDOW_TITLE "Chapter 4: 3D"
#define SHADER_PROGRAM 0
#define SHADER_FRAGMENT 1
#define SHADER_VERTEX 2
#define BUFFER_VAO 0
#define BUFFER_VBO 1
#define BUFFER_IBO 2

/* === GLOBAL VARIABLES === */
GLuint projMatUniLoc, viewMatUniLoc, modelMatUniLoc;
GLuint bufferIds[3] = {0}, shaderIds[3] = {0};
int windowWidth, windowHeight, windowHandle;
float cubeRotation;
clock_t lastTime;
unsigned frames;

/* === MATRIXES === */
Matrix projectionMatrix, viewMatrix, modelMatrix;

/* === FUNCTION PROTOTYPES === */
void init(int, char **);
void initWindow(int, char **);
void resize(int, int);
void render(void);
void timer(int);
void idle(void);
void createCube(void);
void destroyCube(void);
void drawCube(void);

/*
* main():
* Main entry point of the application.
*/
int main(int argc, char **argv) {
/* Initialize everything we need */
init(argc, argv);

/* Start the glut loop */
glutMainLoop();

exit(EXIT_SUCCESS);
}

/*
* init(argc, argv):
* Initializes everything we need to start running.
*/
void init(int argc, char **argv) {
GLenum ret;
/* Create our openGL window */
windowWidth = 1024;
windowHeight = 768;
initWindow(argc, argv);

/* Initialize glew */
ret = glewInit();
if (GLEW_OK != ret) {
fprintf(stderr, "ERROR: %s\n", glewGetErrorString(ret));
exit(EXIT_FAILURE);
}

/* Get the running openGL version */
fprintf(stdout, "INFO: OpenGL Version: %s\n", glGetString(GL_VERSION));

/* Empty potential errors */
glGetError();

/* Clear the screen */
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

/* Enable depth test */
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
ExitOnGLError("ERROR: Could not set OpenGL depth testing");

/* Enable culling of faces */
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
ExitOnGLError("Error: Could not set OpenGL culling");

/* Setup out default matrices */
modelMatrix = IDENTITY_MATRIX;
projectionMatrix = IDENTITY_MATRIX;
viewMatrix = IDENTITY_MATRIX;
TranslateMatrix(&viewMatrix, 0, 0, -2);

/* Create our initial cube */
createCube();
}

/*
* initWindow(argc, argv):
* Create the openGL window for us.
*/
void initWindow(int argc, char **argv) {
/* Initialize glut */
glutInit(&argc, argv);
glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
glutInitWindowSize(windowWidth, windowHeight);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

/* Create the window */
windowHandle = glutCreateWindow(WINDOW_TITLE);
if (windowHandle < 1) {
fprintf(stderr, "ERROR: Could not create window.\n");
exit(EXIT_FAILURE);
}

/* Set glut callback functions */
glutReshapeFunc(resize);
glutDisplayFunc(render);
glutIdleFunc(idle);
glutTimerFunc(0, timer, 0);
glutCloseFunc(destroyCube);
}

/*
* rezie(width, height):
* Resize the openGL window.
*/
void resize(int width, int height) {
/* Save dimensions */
windowWidth = width;
windowHeight = height;

/* Set viewport */
glViewport(0, 0, width, height);

/* Change our projection matrix */
projectionMatrix = CreateProjectionMatrix(60,
(float)windowWidth / windowHeight, 1.0f, 100.0f);
glUseProgram(shaderIds[0]);
glUniformMatrix4fv(projMatUniLoc, 1, GL_FALSE, projectionMatrix.m);
glUseProgram(0);
}

/*
* render()
* Render our openGL scene.
*/
void render(void) {
++frames;

/* Clear screen */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* Draw our cube */
drawCube();

/* Swap buffers and update display */
glutSwapBuffers();
glutPostRedisplay();
}

/*
* idle():
* Logic function.
*/
void idle(void) {
glutPostRedisplay();
}

/*
* timer(val):
* Timer to count FPS.
*/
void timer(int val) {
char fpsString[512];

if (val != 0) {
/* Allocate memory and copy string */
sprintf(fpsString, "%s: %d FPS @ %d x %d", WINDOW_TITLE,
frames * 4, windowWidth, windowHeight);

/* Set it as title */
glutSetWindowTitle(fpsString);
}

frames = 0;
glutTimerFunc(250, timer, 1);
}

/*
* createCube():
* Setup the cube.
*/
void createCube(void) {
const Vertex vertices[8] = {
{{-0.5f, -0.5f, 0.5f, 1}, {0, 0, 1, 1}},
{{-0.5f, 0.5f, 0.5f, 1}, {1, 0, 0, 1}},
{{0.5f, 0.5f, 0.5f, 1}, {0, 1, 0, 1}},
{{0.5f, -0.5f, 0.5f, 1}, {1, 1, 0, 1}},
{{-0.5f, -0.5f, -0.5f, 1}, {1, 1, 1, 1}},
{{-0.5f, 0.5f, -0.5f, 1}, {1, 0, 0, 1}},
{{0.5f, 0.5f, -0.5f, 1}, {1, 0, 1, 1}},
{{0.5f, -0.5f, -0.5f, 1}, {0, 0, 1, 1}}
};
const GLuint indices[36] = {
0, 2, 1, 0, 3, 2, 4, 3, 0, 4, 7, 3,
4, 1, 5, 4, 0, 1, 3, 6, 2, 3, 7, 6,
1, 6, 5, 1, 2, 6, 7, 5, 6, 7, 4, 5
};

/* Generate the shader program */
shaderIds[SHADER_PROGRAM] = glCreateProgram();
ExitOnGLError("ERROR: Could not create shader program");

/* Load and attach shaders */
shaderIds[SHADER_FRAGMENT] = LoadShader("fragment.glsl", GL_FRAGMENT_SHADER);
shaderIds[SHADER_VERTEX] = LoadShader("vertex.glsl", GL_VERTEX_SHADER);
glAttachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_FRAGMENT]);
glAttachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_VERTEX]);

/* Link shader program */
glLinkProgram(shaderIds[SHADER_PROGRAM]);
ExitOnGLError("ERROR: Could not link shader program");

/* Retrive shader uniforms */
modelMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "modelMatrix");
viewMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "viewMatrix");
projMatUniLoc = glGetUniformLocation(shaderIds[SHADER_PROGRAM], "projectionMatrix");
ExitOnGLError("ERROR: Could not get shader uniform locations");

/* Generate and bind our vertex array object */
glGenVertexArrays(1, &bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not generate VAO");
glBindVertexArray(bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not bind VAO");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
ExitOnGLError("ERROR: Could not enable vertex attributes");

/* Bind VBO and send data */
glGenBuffers(2, &bufferIds[BUFFER_VBO]);
glBindBuffer(GL_ARRAY_BUFFER, bufferIds[BUFFER_VBO]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind VBO to VAO");

/* Set the attributes for our VAO */
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (GLvoid *)0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertices[0]),
(GLvoid *)sizeof(vertices[0].Position));
ExitOnGLError("ERROR: Could not set VAO attributes");

/* Bind IBO and send data */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferIds[BUFFER_IBO]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind IBO to VAO");
glBindVertexArray(0);
}

/*
* destroyCube():
* Destroy out little cubie.
*/
void destroyCube(void) {
/* Detach and delete shaders */
glDetachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_FRAGMENT]);
glDetachShader(shaderIds[SHADER_PROGRAM], shaderIds[SHADER_VERTEX]);
glDeleteShader(shaderIds[SHADER_FRAGMENT]);
glDeleteShader(shaderIds[SHADER_VERTEX]);
glDeleteProgram(shaderIds[SHADER_PROGRAM]);
ExitOnGLError("ERROR: Could not destroy shaders");

/* Delete and destroy buffers */
glDeleteBuffers(2, &bufferIds[BUFFER_VBO]);
glDeleteVertexArrays(1, &bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not destroy buffer objects");
}

/*
* drawCube():
* Draw the cube.
*/
void drawCube(void) {
float cubeAngle;
clock_t now;

/* Current time */
now = clock();
if (lastTime == 0)
lastTime = now;

/* Adjust rotation */
cubeRotation += 45.0f * ((float)(now - lastTime) / CLOCKS_PER_SEC);
cubeAngle = DegreesToRadians(cubeRotation);
lastTime = now;

/* Rotate the matrix */
modelMatrix = IDENTITY_MATRIX;
RotateAboutY(&modelMatrix, cubeAngle);
RotateAboutX(&modelMatrix, cubeAngle);

/* Use the shader program so we can manipluate */
glUseProgram(shaderIds[SHADER_PROGRAM]);

/* Adjust matrix uniform locations */
glUniformMatrix4fv(modelMatUniLoc, 1, GL_FALSE, modelMatrix.m);
glUniformMatrix4fv(viewMatUniLoc, 1, GL_FALSE, viewMatrix.m);
ExitOnGLError("ERROR: Could not set the shader uniforms");

/* Bind and draw the VAO */
glBindVertexArray(bufferIds[BUFFER_VAO]);
ExitOnGLError("ERROR: Could not bind VAO for drawing");
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (GLvoid *)0);
ExitOnGLError("ERROR: Could not draw the cube");

/* Done manipulating */
glBindVertexArray(0);
glUseProgram(0);
}




Their code


/* Copyright (C) 2011 by Eddy Luten

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "Utils.h"
#define WINDOW_TITLE_PREFIX "Chapter 4"

int CurrentWidth = 800,
CurrentHeight = 600,
WindowHandle = 0;

unsigned FrameCount = 0;

GLuint
ProjectionMatrixUniformLocation,
ViewMatrixUniformLocation,
ModelMatrixUniformLocation,
BufferIds[3] = { 0 },
ShaderIds[3] = { 0 };

Matrix
ProjectionMatrix,
ViewMatrix,
ModelMatrix;

float CubeRotation = 0;
clock_t LastTime = 0;

void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void ResizeFunction(int, int);
void RenderFunction(void);
void TimerFunction(int);
void IdleFunction(void);
void CreateCube(void);
void DestroyCube(void);
void DrawCube(void);

int main(int argc, char* argv[])
{
Initialize(argc, argv);

glutMainLoop();

exit(EXIT_SUCCESS);
}

void Initialize(int argc, char* argv[])
{
GLenum GlewInitResult;

InitWindow(argc, argv);

glewExperimental = GL_TRUE;
GlewInitResult = glewInit();

if (GLEW_OK != GlewInitResult) {
fprintf(
stderr,
"ERROR: %s\n",
glewGetErrorString(GlewInitResult)
);
exit(EXIT_FAILURE);
}

fprintf(
stdout,
"INFO: OpenGL Version: %s\n",
glGetString(GL_VERSION)
);

glGetError();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
ExitOnGLError("ERROR: Could not set OpenGL depth testing options");

glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
ExitOnGLError("ERROR: Could not set OpenGL culling options");

ModelMatrix = IDENTITY_MATRIX;
ProjectionMatrix = IDENTITY_MATRIX;
ViewMatrix = IDENTITY_MATRIX;
TranslateMatrix(&ViewMatrix, 0, 0, -2);

CreateCube();
}

void InitWindow(int argc, char* argv[])
{
glutInit(&argc, argv);

glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);

glutSetOption(
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);

glutInitWindowSize(CurrentWidth, CurrentHeight);

glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);

if(WindowHandle < 1) {
fprintf(
stderr,
"ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}

glutReshapeFunc(ResizeFunction);
glutDisplayFunc(RenderFunction);
glutIdleFunc(IdleFunction);
glutTimerFunc(0, TimerFunction, 0);
glutCloseFunc(DestroyCube);
}

void ResizeFunction(int Width, int Height)
{
CurrentWidth = Width;
CurrentHeight = Height;
glViewport(0, 0, CurrentWidth, CurrentHeight);
ProjectionMatrix =
CreateProjectionMatrix(
60,
(float)CurrentWidth / CurrentHeight,
1.0f,
100.0f
);

glUseProgram(ShaderIds[0]);
glUniformMatrix4fv(ProjectionMatrixUniformLocation, 1, GL_FALSE, ProjectionMatrix.m);
glUseProgram(0);
}

void RenderFunction(void)
{
++FrameCount;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

DrawCube();

glutSwapBuffers();
glutPostRedisplay();
}

void IdleFunction(void)
{
glutPostRedisplay();
}

void TimerFunction(int Value)
{
if (0 != Value) {
char* TempString = (char*)
malloc(512 + strlen(WINDOW_TITLE_PREFIX));

sprintf(
TempString,
"%s: %d Frames Per Second @ %d x %d",
WINDOW_TITLE_PREFIX,
FrameCount * 4,
CurrentWidth,
CurrentHeight
);

glutSetWindowTitle(TempString);
free(TempString);
}

FrameCount = 0;
glutTimerFunc(250, TimerFunction, 1);
}

void CreateCube()
{
const Vertex VERTICES[8] =
{
{ { -.5f, -.5f, .5f, 1 }, { 0, 0, 1, 1 } },
{ { -.5f, .5f, .5f, 1 }, { 1, 0, 0, 1 } },
{ { .5f, .5f, .5f, 1 }, { 0, 1, 0, 1 } },
{ { .5f, -.5f, .5f, 1 }, { 1, 1, 0, 1 } },
{ { -.5f, -.5f, -.5f, 1 }, { 1, 1, 1, 1 } },
{ { -.5f, .5f, -.5f, 1 }, { 1, 0, 0, 1 } },
{ { .5f, .5f, -.5f, 1 }, { 1, 0, 1, 1 } },
{ { .5f, -.5f, -.5f, 1 }, { 0, 0, 1, 1 } }
};

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

ShaderIds[0] = glCreateProgram();
ExitOnGLError("ERROR: Could not create the shader program");
{
ShaderIds[1] = LoadShader("SimpleShader.fragment.glsl", GL_FRAGMENT_SHADER);
ShaderIds[2] = LoadShader("SimpleShader.vertex.glsl", GL_VERTEX_SHADER);
glAttachShader(ShaderIds[0], ShaderIds[1]);
glAttachShader(ShaderIds[0], ShaderIds[2]);
}
glLinkProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not link the shader program");

ModelMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ModelMatrix");
ViewMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ViewMatrix");
ProjectionMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ProjectionMatrix");
ExitOnGLError("ERROR: Could not get shader uniform locations");

glGenVertexArrays(1, &BufferIds[0]);
ExitOnGLError("ERROR: Could not generate the VAO");
glBindVertexArray(BufferIds[0]);
ExitOnGLError("ERROR: Could not bind the VAO");

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
ExitOnGLError("ERROR: Could not enable vertex attributes");

glGenBuffers(2, &BufferIds[1]);
ExitOnGLError("ERROR: Could not generate the buffer objects");

glBindBuffer(GL_ARRAY_BUFFER, BufferIds[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES), VERTICES, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind the VBO to the VAO");

glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VERTICES[0]), (GLvoid*)0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VERTICES[0]), (GLvoid*)sizeof(VERTICES[0].Position));
ExitOnGLError("ERROR: Could not set VAO attributes");

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferIds[2]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INDICES), INDICES, GL_STATIC_DRAW);
ExitOnGLError("ERROR: Could not bind the IBO to the VAO");

glBindVertexArray(0);
}

void DestroyCube()
{
glDetachShader(ShaderIds[0], ShaderIds[1]);
glDetachShader(ShaderIds[0], ShaderIds[2]);
glDeleteShader(ShaderIds[1]);
glDeleteShader(ShaderIds[2]);
glDeleteProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not destroy the shaders");

glDeleteBuffers(2, &BufferIds[1]);
glDeleteVertexArrays(1, &BufferIds[0]);
ExitOnGLError("ERROR: Could not destroy the buffer objects");
}

void DrawCube(void)
{
float CubeAngle;
clock_t Now = clock();

if (LastTime == 0)
LastTime = Now;

CubeRotation += 45.0f * ((float)(Now - LastTime) / CLOCKS_PER_SEC);
CubeAngle = DegreesToRadians(CubeRotation);
LastTime = Now;

ModelMatrix = IDENTITY_MATRIX;
RotateAboutY(&ModelMatrix, CubeAngle);
RotateAboutX(&ModelMatrix, CubeAngle);

glUseProgram(ShaderIds[0]);
ExitOnGLError("ERROR: Could not use the shader program");

glUniformMatrix4fv(ModelMatrixUniformLocation, 1, GL_FALSE, ModelMatrix.m);
glUniformMatrix4fv(ViewMatrixUniformLocation, 1, GL_FALSE, ViewMatrix.m);
ExitOnGLError("ERROR: Could not set the shader uniforms");

glBindVertexArray(BufferIds[0]);
ExitOnGLError("ERROR: Could not bind the VAO for drawing purposes");

glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (GLvoid*)0);
ExitOnGLError("ERROR: Could not draw the cube");

glBindVertexArray(0);
glUseProgram(0);
}

Thanks, Eddy
Hello again folks, thank you for the fast answers!

I'm not getting any error outputs at all. The thing that "doesn't work" is that the screen is entierly black. The nice little cube is missing.
Omg, zombie! Zomgbie.
Can you post your shaders as well? For one thing its not good to use hardcoded indexes (0/1) for your attribs. You should query the attribute indexes for your shader inputs via glGetAttribLocation, then use the returned value to index it.

I'm not sure you can just assume you can always assign 0 to vertex position unless you're using deprecated shader builtin variables, which I don't know if you are or not.
[size=2]My Projects:
[size=2]Portfolio Map for Android - Free Visual Portfolio Tracker
[size=2]Electron Flux for Android - Free Puzzle/Logic Game
I'm using the same shaders as the example that works:

Vertex:


#version 400

layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
out vec4 ex_Color;

uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;

void main(void)
{
gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
ex_Color = in_Color;
}


Fragment:


#version 400

in vec4 ex_Color;
out vec4 out_Color;

void main(void)
{
out_Color = ex_Color;
}
Omg, zombie! Zomgbie.
You changed the casing in your call to glGetUniformLocation to lower camel case ([color=#660066][font=CourierNew, monospace][size=2]modelMatrix[/font]), while the names of the uniforms in the shaders remain upper camel case ([color=#660066][font=CourierNew, monospace][size=2]ModelMatrix[/font]), that may be why it's not working. Let me know.
Thanks, Eddy
Thank you, that was the problem!

I'd also like to thank you for those awesome guides. They are very helpfull and well written <3
Omg, zombie! Zomgbie.
Excellent, and thanks :)
Thanks, Eddy
I even didn't know that such website exists.
Will there be more than 4 chapters?

Or that's all?
Big .com website for only 4 chapters is pretty expensive.


But if you're going to expand it, then it's good.

This topic is closed to new replies.

Advertisement