# OpenGL [FIXED]Open simple obj file -> nothing

This topic is 1240 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,

I tried to set myself a not to hard challenge since I'm in a early stage of learning OpenGL.

My goal was to be able to load simple obj file without the texture and then add the texture etc.

I parse the file correctly but I always have nothing displayed but not error, but I can still draw manually a triangle etc.

I am going to put my simple init and draw code below and also the results of a parsed file (only the vertices position).

But this is my question : Do I need to do something "special" to display an object from a obj file ?

Init :

void init(){

programHandle = glCreateProgram();
if (0 == programHandle)
{
fprintf(stderr, "Error creating program object.\n");
exit(1);
}

glUseProgram(programHandle);

//setup element array buffer
glGenBuffers(2, vboHandles);
glBindBuffer(GL_ARRAY_BUFFER, vboHandles[0]);
glBufferData(GL_ARRAY_BUFFER, obj.getVertexNumber() * 4 * sizeof(GLfloat), obj.getVertexCoords()->data(), GL_STATIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, vboHandles[1]);
glBufferData(GL_ARRAY_BUFFER, obj.getVertexNumber()*3 * sizeof(GLfloat), obj.getNormals()->data(), GL_STATIC_DRAW);

glGenVertexArrays(1, &vaoHandle);
glBindVertexArray(vaoHandle);

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER, vboHandles[0]);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);

glBindBuffer(GL_ARRAY_BUFFER, vboHandles[1]);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);

}

draw :

void draw(){
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vaoHandle);
glDrawArrays(GL_TRIANGLES, 0, obj.getVertexNumber());
glFlush();
}

A parsed file vertices position (cube in blender) :

1, -1, -1, 1,
1, -1, 1, 1,
-1, -1, 1, 1,
-1, -1, -1, 1,
1, 1, -1, 1,
1, 1, 1, 1,
-1, 1, 1, 1,
-1, 1, -1, 1


I hope someone will be able to help me

rXp

##### Share on other sites

"Do I need to do something "special" to display an object from a obj file ?"

You just need to parse the file correctly, once you got the file data into memory it doesn't matter what format the file was. With the file data you should be able to prepare the buffers you need to pass to the OpenGL functions.

If you have any doubt, try the same code but instead of reading the OBJ file, hard code the vertices. If you see something then your problem is on the parsing or the array construction, if you still see nothing then the problem is elsewhere. Can you draw a single triangle with your current code?

I've never used buffers with OpenGL so I can't follow that code, but I guess the rest of the code will be usefull for other users.

Also, learn how to use a debugger, and set a breakpoint to make sure that the values you read from the file are still there in the arrays when setting the buffer data.

Edited by DiegoSLTS

##### Share on other sites

The values are correct and the last "code" is a file that I parsed and printed (so 100% correct).

Outside from that, yes I can draw a simple triangle.

##### Share on other sites

debugging is the most important skill to learn:

so start by walking thru the code and see if it matches exactly with what you think it is doing.

A few things jump out at me:

the 4 in

glBufferData(GL_ARRAY_BUFFER, obj.getVertexNumber() * 4 * sizeof(GLfloat), obj.getVertexCoords()->data(), GL_STATIC_DRAW);

the GL_TRIANGLES in

glDrawArrays(GL_TRIANGLES, 0, obj.getVertexNumber());

should the 4 be 3? why should it be 3?

And the parsed file vert positions looks off:

say like what does 1, -1, -1, 1,  represent?

I was expecting to see something like 1,-1,1 to represent say the (xyz) coordinates of a vert.

Edited by steven katic

##### Share on other sites

Since the W is optional in obj, if there is none I add it to 1.0f myself. That's why there is X,Y,Z,W everytime.

Edited by rXpSwiss

##### Share on other sites

diegoSTLS makes a good point: "You just need to parse the file correctly, once you got the file data into memory it doesn't matter what format the file was."

And why should the 4 be a 3? (maybe I haven't given enough hints?)

Edited by steven katic

##### Share on other sites

Okey, I see changes now but let me explain how I thought :

When I parse a obj file there can be 4 values for each vertex position (x,y,z,w), since the W is optional I decided to get it if it is specified or to set it to 1.0f if it is not specified.

This means after parsing I always have 4 values for a vertex position.

When I wrote that

glBufferData(GL_ARRAY_BUFFER, obj.getVertexNumber() * 4 * sizeof(GLfloat), obj.getVertexCoords()->data(), GL_STATIC_DRAW);

I thought : "Okey, there is X vertices with 4 floating values, hence X * 4 * sizeof(GLfloat)" and this is the reason I also set the glVertexAttribPointer to "0,4,..." because I want to give a vec4 my basic vertex shader so it can simply set it to gl_position.

I understand that it is wrong but I don't understand why. What is wrong in my train of thought ?

Edited by rXpSwiss

##### Share on other sites

what changes did you see?

##### Share on other sites

now might be a good time to get really familiar with glDrawArrays and gldrawelements. look for as many examples as you need to.

you ultimately will end up explicitly specifiying the structure of your data in a format that is restricted by opengl function specs:

typically when you specify GL_TRIANGLES your data should conform to a "set of 3 floats in the array of floats represents a vertex of a triangle".

edit: and so every sequence of 3 verts (of 3 floats) will represent a triangle.

another useful thing to research now would be arrays of structures vs structures of arrays.

I feel I am still being a little bit vague here, so I welcome anyone to be more succinct and specific with an explanation for the OP.

Still... I hope this helps

Edited by steven katic

##### Share on other sites

Can you share the code where you create the array? How are you using the faces data from the file?

##### Share on other sites

Can you share the code where you create the array? How are you using the faces data from the file?

This. You are sending the 8 vertices of a cube to GL, but drawing triangles that's not going to work (cube has 6 faces that are quads = 12 total triangles). You need to make a GL_ELEMENT_ARRAY buffer out of the faces section of the obj file data.

If you haven't already seen this online book, stop now and read: http://arcsynthesis.org/gltut/

##### Share on other sites

scratch all of that. Just realize something... I feel stupide

Edited by rXpSwiss

##### Share on other sites

I everyone, after reviewing my code and your advice I finally have a semi-working thing :)

Why do I say semi ? Because the model is loaded and I see something but there is an issue : ALL polygon seem to me drawn from the origin point.

It is supposed to be Suzanne (Blender monkey head).

What could do that ?

Draw code :

void draw(){

//matrix uniform

GLuint mID = glGetUniformLocation(programHandle, "m");
glUniformMatrix4fv(mID, 1, GL_FALSE, &model[0][0]);

GLuint vID = glGetUniformLocation(programHandle, "v");
glUniformMatrix4fv(vID, 1, GL_FALSE, &view[0][0]);

GLuint pID = glGetUniformLocation(programHandle, "p");
glUniformMatrix4fv(pID, 1, GL_FALSE, &projection[0][0]);

GLuint itID = glGetUniformLocation(programHandle, "invTransp");
glUniformMatrix4fv(itID, 1, GL_FALSE, &glm::transpose(glm::inverse(model))[0][0]);

glClear(GL_COLOR_BUFFER_BIT);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,vboIndex);
std::vector<GLuint>* order = new std::vector<GLuint>;
obj.getVertexOrder(order);
//glDisable(GL_CULL_FACE);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//glDisable(GL_LIGHTING);
//glDisable(GL_TEXTURE_2D);

glDrawElements(GL_POLYGON, order->size(), GL_UNSIGNED_INT, 0);
glFlush();
}


Thank you for your help :) I very new to opengl and it is not easy to search when that happens if I don't know how this is called xD

##### Share on other sites

GL_POLYGON draws a *single* polygon. Try hitting 'triangulate' in blender before exporting to obj and rendering GL_TRIANGLES.

##### Share on other sites

I did just what you said it helped a bit. I can see the face now but it is not hole/it is like the faces subtract each other.

What else should I try ?

##### Share on other sites

Have you set up the depth buffer?

Needs to be enabled, cleared each frame, and the most common clear value is 1.0.

Here's a wiki page about is: http://www.opengl.org/wiki/Depth_Buffer

edit: also obj indices start at 1, need to adjust to 0 for gl elements if you haven't already.

Edited by beans222

##### Share on other sites

You were right it was the depth buffer. Thank you, I thought it was enable by default. :)

• 12
• 10
• 11
• 18
• 13
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?