• Advertisement
Sign in to follow this  

OpenGL Error in the .obj loader

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to write an .obj file format loader for my OpenGL based engine. But models that I load aren't looking properly and I just can't find the problem. I'll be glad if someone can help me. Here's the code:
#include <iostream>
#include <fstream>
#include <vector>
#include "re_renderer.h"
#include "re_math.h"

#pragma once

class COBJModel: public CTexture
{
public:
	COBJModel();

	void load(const char *objFile);
	void loadDiffuseMap(const char *diffuseMapFile);
	void render(void);
private:
	vector <int> triangleData;
	vector <float> vertices;
	vector <float> texCoords;
	vector <float> normals;
	vector <float> vertexArray;
	vector <float> texCoordArray;
	vector <float> normalArray;
	GLuint diffuseTexture;
	
	int x, y, z, nx, ny, nz, tx, ty, tz;
	float a, b, c, na, nb, nc, u, v;
};




#include "re_objloader.h"

COBJModel::COBJModel()
{
	x = 0;
	y = 0;
	z = 0;
	nx = 0;
	ny = 0;
	nz = 0;
	tx = 0;
	ty = 0;
	tz = 0;
	a = 0;
	b = 0;
	c = 0;
	na = 0;
	nb = 0;
	nc = 0;
	u = 0;
	v = 0;
}

void COBJModel::load(const char *objFile)
{
	int i = 0;
	ifstream modelFile;
	string line;
	
	modelFile.open(objFile, ios::in);    
	if (!modelFile.fail())
    {
        while (!modelFile.eof())
        {
			getline(modelFile, line);
			const char* data = line.c_str();

			if(data[0] == 'v' && data[1] == ' ')
			{
				sscanf(data, "v %f %f %f", &a, &b, &c);
				vertices.push_back(a);
				vertices.push_back(b);
				vertices.push_back(c);
			}

			else if(data[0] == 'v' && data[1] == 'n')
			{
				sscanf(data, "vn %f %f %f", &na, &nb, &nc);
				normals.push_back(na);
				normals.push_back(nb);
				normals.push_back(nc);
			}
			
			else if(data[0] == 'v' && data[1] == 't')
			{
				sscanf(data, "vt %f %f", &u, &v);
				texCoords.push_back(u);
				texCoords.push_back(v);
			}
		
			else if(data[0] == 'f')
			{
				sscanf(data, "f %d/%d/%d %d/%d/%d %d/%d/%d", &x, &tx, &nx, &y, &ty, &ny, &z, &tz, &nz);
				triangleData.push_back(x);
				triangleData.push_back(y);
				triangleData.push_back(z);
				triangleData.push_back(tx);
				triangleData.push_back(ty);
				triangleData.push_back(tz);
				triangleData.push_back(nx);
				triangleData.push_back(ny);
				triangleData.push_back(nz);
			}

			else if(data[0] == 's')
			{
			}

			else if(data[0] == 'g')
			{
			}

			else if(data[0] == 'm')
			{
			}

			else if(data[0] == 'u')
			{
			}
		}

		for(int i = 0; i < triangleData.size() / 9; i++)
		{
			vertexArray.push_back(vertices[triangleData[9 * i]]);
			vertexArray.push_back(vertices[triangleData[(9 * i) + 1]]);
			vertexArray.push_back(vertices[triangleData[(9 * i) + 2]]);
			texCoordArray.push_back(texCoords[triangleData[(9 * i) + 3]]);
			texCoordArray.push_back(texCoords[triangleData[(9 * i) + 4]]);
			texCoordArray.push_back(texCoords[triangleData[(9 * i) + 5]]);
			normalArray.push_back(normals[triangleData[(9 * i) + 6]]);
			normalArray.push_back(normals[triangleData[(9 * i) + 7]]);
			normalArray.push_back(normals[triangleData[(9 * i) + 8]]);
		}
		cout << "Loaded model \"" << objFile << "\"" << endl;
    }
	else
		cout << "Could not load model \"" << objFile << "\"" << endl;
	modelFile.close();
}

void COBJModel::loadDiffuseMap(const char *diffuseMapFile)
{
	diffuseTexture = loadTexture(diffuseMapFile);
}

void COBJModel::render()
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, diffuseTexture);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_NORMAL_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);
	glTexCoordPointer(3, GL_FLOAT, 0, &texCoordArray[0]);
	glNormalPointer(GL_FLOAT, 0, &normalArray[0]);
	glVertexPointer(3, GL_FLOAT, 0, &vertexArray[0]);
	glDrawArrays(GL_TRIANGLES, 0, vertexArray.size());
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisable(GL_TEXTURE_2D);
}






And this is the result that I am getting(it's supposed to be a trash can :) ): http://img204.imageshack.us/my.php?image=newbitmapimagebm7.jpg

Share this post


Link to post
Share on other sites
Advertisement
Face indices in .obj files start at 1, IIRC, whereas you want them to start at 0, so you could try:


triangleData.push_back(x-1);
triangleData.push_back(y-1);
triangleData.push_back(z-1);
// ...

Share this post


Link to post
Share on other sites
Quote:
Original post by sprite_hound
Face indices in .obj files start at 1, IIRC, whereas you want them to start at 0, so you could try:


triangleData.push_back(x-1);
triangleData.push_back(y-1);
triangleData.push_back(z-1);
// ...


You are right, I forgot about that. Unfortunately it's still not working. I think there's another error in the code. I'll look onto it. Thanks by the way.

Share this post


Link to post
Share on other sites
You push U and V onto the texCoords-array, but you pass 3 as the number of coordinates per element as the first argument to glTexCoordPointer().

Share this post


Link to post
Share on other sites
Faces in the .obj files are like this:

f 710/107/273 711/108/273 712/105/273
(vert)/(text)/(norm)

But texture coordinates are like this:
vt 0.831538 0.449444
(u) (v)

I guessed that if there are 3 texture coordinates per face, I should initialize the pointer with 3 elements.

And I tried to draw the model with just vertices and it's still not working:

glBegin(GL_TRIANGLES);
for(unsigned int i = 0; i < vertexArray.size() - 2; i++)
{
glVertex3f(vertexArray, vertexArray[i + 1], vertexArray[i + 2]);
}
glEnd();

Share this post


Link to post
Share on other sites
Well that looks like a bit of a pickle. I'll have a guess too:
I would next try something like this(just looking at vertex indices for the moment):


for(int i = 0; i < triangleData.size() / 9; i++)
{
int vertIndex1 = triangleData[9 * i]*3;
vertexArray.push_back(vertices[vertIndex1]);
vertexArray.push_back(vertices[vertIndex1 + 1]);
vertexArray.push_back(vertices[vertIndex1 + 2]);

int vertIndex2 = triangleData[[(9 * i) + 1]*3;
vertexArray.push_back(vertices[vertIndex2]);
vertexArray.push_back(vertices[vertIndex2 + 1]);
vertexArray.push_back(vertices[vertIndex2 + 2]);

int vertIndex3 = triangleData[[(9 * i) + 2]*3;
vertexArray.push_back(vertices[vertIndex3]);
vertexArray.push_back(vertices[vertIndex3 + 1]);
vertexArray.push_back(vertices[vertIndex3 + 2]);

... //etc, etc
...
...
}



It's based on the premise that each index in triangleData is a vertex index (as we know) and vertices are not really vertices: but every set of 3 floats in vertices is actually a vertex. I won't go into details,...but IF the code does solve your problem a careful walkthru of the code should uncover/clarify, in your own mind, this type of tedious detail that can be easily overlooked.

If that doesn't help, what next then... hmmmm?

Share this post


Link to post
Share on other sites
Quote:
Original post by steven katic
Well that looks like a bit of a pickle. I'll have a guess too:
I would next try something like this(just looking at vertex indices for the moment):

*** Source Snippet Removed ***

It's based on the premise that each index in triangleData is a vertex index (as we know) and vertices are not really vertices: but every set of 3 floats in vertices is actually a vertex. I won't go into details,...but IF the code does solve your problem a careful walkthru of the code should uncover/clarify, in your own mind, this type of tedious detail that can be easily overlooked.

If that doesn't help, what next then... hmmmm?


Yes, that solved it. I didn't think that way. Thank you very much. After I do the same to TexCoords and Normals, I'll update the code in my first post so maybe it helps someone else too :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      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
      Thanks in advance
    • 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:
      Vertex Shader:
      #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
       
    • By dpadam450
      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;
    • By Devashish Khandelwal
      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?
  • Advertisement