Sign in to follow this  

OpenGL OpenGL 3.2 and SDL 1.3

Recommended Posts

Fugitive    150
Hi guys, I have been trying to run some simple OpenGL 3.2 tutorials with SDL 1.3, and have been running into some strange problems. My hunch is that its is a memory-leak, but could be something else. The problem, stripped down to its bare minimum is Tutorial 4 (from here: ) I have only included a header file to initialize opengl extensions (since the original tutorial doesnt do that), and removed gl3.h in favour of gl.h, and glext.h. In addition, here is the init code:
if (initGLExtensions() == false)
		sdldie("Unable to load openGL extensions");
I am presented with a blank white screen. Here is the Visual Studio project: (Its about 5-6 mb) The strange thing is, it compiles fine with Borland C++ Builder 2009 and 2010 (trial edition), but then causes memory leaks further down the line when I try to expand the code. Any ideas? Kind regards, Fugi

Share this post

Link to post
Share on other sites
karwosts    840
Can you please be more descriptive what the problem is?

You said you got a white screen, is that not what you expect to see? Why do you think you have a leak? Is your program crashing?

It would probably help you to post some relevant code sections (in source tag) so we could look over it. I'd would normally be happy to review your code but I'm not going to go bother with rapidshare to look it over.

Share this post

Link to post
Share on other sites
Fugitive    150
The rapidshare link has a 'free user' download link, which allows you to download with only a 28 second wait. How about easyshare: GL test

In any event, the program is supposed to show some triangles, and a geometry shader that turns it into a closed 3d shape. Instead, the window remains blank until the loop is over, then the window closes without any error or warning.

What leads me to believe there is a memory leak is the compiled version on C++ builder. It compiles fine, however, simple things such as

char *test="test";
string x;
x=test; // <===commenting this line makes it show something again!

would cause the program to display a blank screen. No crash nothing. If i comment those lines out, viola, I see the model again. Or something like trying to append more than 2000 bytes would suddenly cause the program to go 'blank' again. Reducing the number of bytes (and recompiling) would show the model. At first I thought there was something weird with the STL string class, but then if I removed all strings, it would give me weird errors further down the line (in code that was working before) related to heap damage when I would try to free memory previously allocated.

To me, those things seem like standard memory-leaking symptoms...subtle, hard-to-track, and constantly moving. Whats worrying though, is that I have removed almost all of my own code, so the memory leak is either in the tutorial, or SDL!

Kind regards,

Share this post

Link to post
Share on other sites
Fugitive    150
Some source: tutorialmain.cpp

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "MyOpenGLExtensions.h"

/* Ensure we are using opengl's core profile only */
//#define GL3_PROTOTYPES 1
//#include <GL3/gl3.h>
#include <gl\gl.h>

#include <SDL\SDL.h>
#include <math.h>

#include "utils.h"

void setupwindow(SDL_WindowID *window, SDL_GLContext *context)
if (SDL_Init(SDL_INIT_VIDEO) < 0) /* Initialize SDL's Video subsystem */
sdldie("Unable to initialize SDL"); /* Or die on error */

/* Request an opengl 3.2 context.
* SDL doesn't have the ability to choose which profile at this time of writing,
* but it should default to the core profile */


/* Enable double buffering with a 24bit Z buffer.
* You may need to change this to 16 or 32 for your system */

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

/* Enable multisampling for a nice antialiased effect */

/* Create our window centered at 512x512 resolution */
if (!*window) /* Die if creation failed */
sdldie("Unable to create window");

/* Create our opengl context and attach it to our window */
*context = SDL_GL_CreateContext(*window);

if (initGLExtensions() == false)
sdldie("Unable to load openGL extensions");

/* This makes our buffer swap syncronized with the monitor's vertical refresh */

/* Enable Z depth testing so objects closest to the viewpoint are in front of objects further away */

void drawscene(SDL_WindowID window)
int i; /* Simple iterator */
GLuint vao, vbo[3]; /* Create handles for our Vertex Array Object and three Vertex Buffer Objects */
GLfloat projectionmatrix[16]; /* Our projection matrix starts with all 0s */
GLfloat modelmatrix[16]; /* Our model matrix */
/* An identity matrix we use to perform the equivalant of glLoadIdentity */
const GLfloat identitymatrix[16] = IDENTITY_MATRIX4;

/* The four vericies of a tetrahedron */
const GLfloat tetrahedron[4][3] = {
{ 1.0, 1.0, 1.0 }, /* index 0 */
{ -1.0, -1.0, 1.0 }, /* index 1 */
{ -1.0, 1.0, -1.0 }, /* index 2 */
{ 1.0, -1.0, -1.0 } }; /* index 3 */

/* Color information for each vertex */
const GLfloat colors[4][3] = {
{ 1.0, 0.0, 0.0 }, /* red */
{ 0.0, 1.0, 0.0 }, /* green */
{ 0.0, 0.0, 1.0 }, /* blue */
{ 1.0, 1.0, 1.0 } }; /* white */

const GLubyte tetraindicies[6] = { 0, 1, 2, 3, 0, 1 };

/* These pointers will receive the contents of our shader source code files */
GLchar *vertexsource, *fragmentsource, *geometrysource;

/* These are handles used to reference the shaders */
GLuint vertexshader, fragmentshader, geometryshader;

/* This is a handle to the shader program */
GLuint shaderprogram;

/* Allocate and assign a Vertex Array Object to our handle */
glGenVertexArrays(1, &vao);

/* Bind our Vertex Array Object as the current used object */

/* Allocate and assign three Vertex Buffer Objects to our handle */
glGenBuffers(3, vbo);

/* Bind our first VBO as being the active buffer and storing vertex attributes (coordinates) */
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);

/* Copy the vertex data from tetrahedron to our buffer */
/* 12 * sizeof(GLfloat) is the size of the tetrahedrom array, since it contains 12 GLfloat values */
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), tetrahedron, GL_STATIC_DRAW);

/* Specify that our coordinate data is going into attribute index 0, and contains three floats per vertex */
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);

/* Enable attribute index 0 as being used */

/* Bind our second VBO as being the active buffer and storing vertex attributes (colors) */
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);

/* Copy the color data from colors to our buffer */
/* 12 * sizeof(GLfloat) is the size of the colors array, since it contains 12 GLfloat values */
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), colors, GL_STATIC_DRAW);

/* Specify that our color data is going into attribute index 1, and contains three floats per vertex */
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);

/* Enable attribute index 1 as being used */

/* Bind our third VBO as being the active buffer and storing vertex array indicies */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[2]);

/* Copy the index data from tetraindicies to our buffer
* 6 * sizeof(GLubyte) is the size of the index array, since it contains 6 GLbyte values */

glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLubyte), tetraindicies, GL_STATIC_DRAW);

/* Read our shaders into the appropriate buffers */
vertexsource = filetobuf("tutorial4.vert");
geometrysource = filetobuf("tutorial4.geom");
fragmentsource = filetobuf("tutorial4.frag");

/* Assign our handles a "name" to new shader objects */
vertexshader = glCreateShader(GL_VERTEX_SHADER);
geometryshader = glCreateShader(GL_GEOMETRY_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);

/* Associate the source code buffers with each handle */
glShaderSource(vertexshader, 1, (const GLchar**)&vertexsource, 0);
glShaderSource(geometryshader, 1, (const GLchar**)&geometrysource, 0);
glShaderSource(fragmentshader, 1, (const GLchar**)&fragmentsource, 0);

/* Compile our shader objects */

/* Assign our program handle a "name" */
shaderprogram = glCreateProgram();

/* Attach our shaders to our program */
glAttachShader(shaderprogram, vertexshader);
glAttachShader(shaderprogram, geometryshader);
glAttachShader(shaderprogram, fragmentshader);

/* Bind attribute 0 (coordinates) to in_Position and attribute 1 (colors) to in_Color */
glBindAttribLocation(shaderprogram, 0, "in_Position");
glBindAttribLocation(shaderprogram, 1, "in_Color");

/* Link our program, and set it as being actively used */

/* Create our projection matrix with a 45 degree field of view
* a width to height ratio of 1 and view from .1 to 100 infront of us */

perspective(projectionmatrix, 45.0, 1.0, 0.1, 100.0);

/* Loop our display rotating our model more each time. */
for (i=0; i < 360; i++)
/* Load the identity matrix into modelmatrix. rotate the model, and move it back 5 */
memcpy(modelmatrix, identitymatrix, sizeof(GLfloat) * 16);
rotate(modelmatrix, (GLfloat)i * -1.0, X_AXIS);
rotate(modelmatrix, (GLfloat)i * 1.0, Y_AXIS);
rotate(modelmatrix, (GLfloat)i * 0.5, Z_AXIS);
translate(modelmatrix, 0, 0, -5.0);

/* multiply our modelmatrix and our projectionmatrix. Results are stored in modelmatrix */
multiply4x4(modelmatrix, projectionmatrix);

/* Bind our modelmatrix variable to be a uniform called mvpmatrix in our shaderprogram */
glUniformMatrix4fv(glGetUniformLocation(shaderprogram, "mvpmatrix"), 1, GL_FALSE, modelmatrix);

/* Make our background black */
glClearColor(0.0, 0.0, 0.0, 1.0);

/* Invoke glDrawElements telling it to draw a triangle strip using 6 indicies */

/* Swap our buffers to make our changes visible */

/* Sleep for roughly 33 milliseconds between frames */

/* Cleanup all the things we bound and allocated */
glDetachShader(shaderprogram, vertexshader);
glDetachShader(shaderprogram, geometryshader);
glDetachShader(shaderprogram, fragmentshader);
glDeleteBuffers(3, vbo);
glDeleteVertexArrays(1, &vao);

void destroywindow(SDL_WindowID window, SDL_GLContext context)

/* Our program's entry point */
int main(int argc, char *argv[])
SDL_WindowID mainwindow; /* Our window handle */
SDL_GLContext maincontext; /* Our opengl context handle */

/* Create our window, opengl context, etc... */
setupwindow(&mainwindow, &maincontext);

/* Call our function that performs opengl operations */

/* Delete our opengl context, destroy our window, and shutdown SDL */
destroywindow(mainwindow, maincontext);

return 0;



#ifndef MyOpenGLExtensionsH
#define MyOpenGLExtensionsH

#include <windows.h>
#include <gl\gl.h>
#include <gl\glext.h>

//int initGLExtensions(); //function prototype


int initGLExtensions()
glCreateShader = (PFNGLCREATESHADERPROC) wglGetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC) wglGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC) wglGetProcAddress("glCompileShader");
glCreateProgram = (PFNGLCREATEPROGRAMPROC) wglGetProcAddress("glCreateProgram");
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC) wglGetProcAddress("glDeleteVertexArrays");

glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) wglGetProcAddress("glUniformMatrix4fv");

if(glGenVertexArrays == NULL)
int x =0;

if (glCreateShader == NULL || glShaderSource == NULL || glCompileShader == NULL
|| glCreateProgram == NULL || glAttachShader == NULL || glLinkProgram == NULL
|| glUseProgram==NULL || glGetShaderiv == NULL || glDetachShader == NULL
|| glDeleteShader == NULL || glDeleteProgram == NULL || glIsShader == NULL
|| glIsProgram == NULL || glGetUniformLocation == NULL || glUniform1f == NULL
|| glUniform1i == NULL
return 0;
else if(glGenBuffers == NULL || glGenFramebuffers == NULL || glBindBuffer == NULL || glBindFramebuffer == NULL
|| glGenRenderbuffers == NULL || glBindRenderbuffer == NULL || glRenderbufferStorage == NULL
|| glFramebufferTexture2D == NULL || glFramebufferRenderbuffer == NULL || glCheckFramebufferStatus == NULL
|| glDeleteFramebuffers == NULL|| glDeleteRenderbuffers == NULL || glActiveTexture == NULL
|| glBufferData == NULL || glDrawBuffers == NULL || glDeleteBuffers == NULL
return 0;
else if(glVertexAttribPointer == NULL || glEnableVertexAttribArray == NULL || glDisableVertexAttribArray == NULL
|| glBindAttribLocation == NULL || glClampColor == NULL || glMultiTexCoord2f == NULL
|| glGenVertexArrays == NULL || glBindVertexArray==NULL || glDeleteVertexArrays==NULL)
return 0;

else if(glUniformMatrix4fv == NULL)
return 0;

return 1;



#pragma hdrstop
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GL3_PROTOTYPES 1
#include <GL3/gl3.h>
#include <SDL/SDL.h>
#include <math.h>

#include "utils.h"

/* Multiply 4x4 matrix m1 by 4x4 matrix m2 and store the result in m1 */
void multiply4x4(GLfloat *m1, GLfloat *m2)
GLfloat temp[16];

int x,y;

for (x=0; x < 4; x++)
for(y=0; y < 4; y++)
temp[y + (x*4)] = (m1[x*4] * m2[y]) +
(m1[(x*4)+1] * m2[y+4]) +
(m1[(x*4)+2] * m2[y+8]) +
(m1[(x*4)+3] * m2[y+12]);

memcpy(m1, temp, sizeof(GLfloat) * 16);

/* Generate a perspective view matrix using a field of view angle fov,
* window aspect ratio, near and far clipping planes */

void perspective(GLfloat *matrix, GLfloat fov, GLfloat aspect, GLfloat nearz, GLfloat farz)
GLfloat range;

range = tan(fov * 0.00872664625) * nearz; /* 0.00872664625 = PI/360 */
memset(matrix, 0, sizeof(GLfloat) * 16);
matrix[0] = (2 * nearz) / ((range * aspect) - (-range * aspect));
matrix[5] = (2 * nearz) / (2 * range);
matrix[10] = -(farz + nearz) / (farz - nearz);
matrix[11] = -1;
matrix[14] = -(2 * farz * nearz) / (farz - nearz);

/* Perform translation operations on a matrix */
void translate(GLfloat *matrix, GLfloat x, GLfloat y, GLfloat z)
GLfloat newmatrix[16] = IDENTITY_MATRIX4;

newmatrix[12] = x;
newmatrix[13] = y;
newmatrix[14] = z;

multiply4x4(matrix, newmatrix);

/* Rotate a matrix by an angle on a X, Y, or Z axis */
void rotate(GLfloat *matrix, GLfloat angle, AXIS axis)
const GLfloat d2r = 0.0174532925199; /* PI / 180 */
const int cos1[3] = { 5, 0, 0 };
const int cos2[3] = { 10, 10, 5 };
const int sin1[3] = { 6, 2, 1 };
const int sin2[3] = { 9, 8, 4 };
GLfloat newmatrix[16] = IDENTITY_MATRIX4;

newmatrix[cos1[axis]] = cos(d2r * angle);
newmatrix[sin1[axis]] = -sin(d2r * angle);
newmatrix[sin2[axis]] = -newmatrix[sin1[axis]];
newmatrix[cos2[axis]] = newmatrix[cos1[axis]];

multiply4x4(matrix, newmatrix);

/* A simple function that will read a file into an allocated char pointer buffer */
char* filetobuf(char *file)
FILE *fptr;
long length;
char *buf;

fptr = fopen(file, "r"); /* Open file for reading */
if (!fptr) /* Return NULL on failure */
return NULL;
fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */
length = ftell(fptr); /* Find out how many bytes into the file we are */
buf = (char*)malloc(length + 1); /* Allocate a buffer for the entire length of the file plus a null terminator */
fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */
fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */
fclose(fptr); /* Close the file */
buf[length] = 0; /* Null terminator */

return buf; /* Return the buffer */

/* A simple function that prints a message, the error code returned by SDL, and quits the application */
void sdldie(char *msg)
printf("%s: %s\n", msg, SDL_GetError());

Share this post

Link to post
Share on other sites
A_B    122
forgive me if i'm wrong but shouldn't:
Contain a pointer to your object you want to draw?
Nowhere in your drawscene() function do you actually draw the things you defined. (as far as i can see, i'm by no means a pro)


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By povilaslt2
      Hello. I'm Programmer who is in search of 2D game project who preferably uses OpenGL and C++. You can see my projects in GitHub. Project genre doesn't matter (except MMO's :D).
    • By ZeldaFan555
      Hello, My name is Matt. I am a programmer. I mostly use Java, but can use C++ and various other languages. I'm looking for someone to partner up with for random projects, preferably using OpenGL, though I'd be open to just about anything. If you're interested you can contact me on Skype or on here, thank you!
      Skype: Mangodoor408
    • By tyhender
      Hello, my name is Mark. I'm hobby programmer. 
      So recently,I thought that it's good idea to find people to create a full 3D engine. I'm looking for people experienced in scripting 3D shaders and implementing physics into engine(game)(we are going to use the React physics engine). 
      And,ye,no money =D I'm just looking for hobbyists that will be proud of their work. If engine(or game) will have financial succes,well,then maybe =D
      Sorry for late replies.
      I mostly give more information when people PM me,but this post is REALLY short,even for me =D
      So here's few more points:
      Engine will use openGL and SDL for graphics. It will use React3D physics library for physics simulation. Engine(most probably,atleast for the first part) won't have graphical fron-end,it will be a framework . I think final engine should be enough to set up an FPS in a couple of minutes. A bit about my self:
      I've been programming for 7 years total. I learned very slowly it as "secondary interesting thing" for like 3 years, but then began to script more seriously.  My primary language is C++,which we are going to use for the engine. Yes,I did 3D graphics with physics simulation before. No, my portfolio isn't very impressive. I'm working on that No,I wasn't employed officially. If anybody need to know more PM me. 
    • By Zaphyk
      I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?
    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
  • Popular Now