Sign in to follow this  
hikarihe

OpenGL importing .obj file into OpenGL

Recommended Posts

hikarihe    243

Hi everyone, when I import an .obj file I get a model looking similar to the one I want but some triangles look distorted.

 

this is the model

[sharedmedia=core:attachments:13638]
 
and this is what i get (ignore rotation)
[sharedmedia=core:attachments:13637]

 

declarations:

// vertex, normal, and index related declarations
GLfloat vertices[500];
GLfloat normals[540];
int indices[1300];
int vertexIndex = 0, normalIndex = 0, elementIndex = 0;

 

 

my load function:

// extracts object's vertices, indices, and normals from given file
int LoadObject( const char* filename, GLfloat vertices[], GLfloat normals[], int elements[] )
{
	// local variables
	const int MAX_CHARS_PER_LINE = 64;
	char lineBuffer[64];
	char temp[16];
	char tempFloat[16];
	FILE *objFile;
	int count;
	GLfloat coordinate; // stored in vertices
	int index;
	int charCount;
	int isVertex = -1; // -1 for normal, 1 for vertex
	int isFirstNormal = 1; // 1 for first normal, -1 for any other normal

	// open file
	fopen_s( &objFile, filename, "r" );

	// check for errors
	if ( objFile == NULL )
	{
		return 0;
	}

	// while there are lines to read
	while ( fgets( lineBuffer, MAX_CHARS_PER_LINE, objFile ) != NULL )
	{
		
		// if we are reading a vector
		if ( strncmp( lineBuffer, "v ", 2 ) == 0 )
		{

			// initialize charCount
			charCount = 0;

			// loop through each char in the line
			for ( count = 2; count < (int)strlen( lineBuffer ); count++ )
			{
				
				// if we are reading part of a float coordinate
				if ( ( lineBuffer[count] == '-' ) || ( isdigit( lineBuffer[count] ) ) || ( lineBuffer[count] == '.') )
				{
					// store this char into temp
					temp[charCount++] = lineBuffer[count];
				}

				// if we are not reading part of a float and a float exists in temp
				else if ( charCount != 0 )
				{
					// copy the float coordinate to tempFloat
					strncpy( tempFloat, temp, charCount );

					//
					tempFloat[ charCount ] = '\n';

					// store the coordinate in our vertices array
					coordinate = atof( tempFloat );
					vertices[vertexIndex++] = coordinate;

					// re-initialize charCount
					charCount = 0;
				}
			}
		}

		// if we are reading a normal
		if ( strncmp( lineBuffer, "vn ", 3 ) == 0 )
		{

			// initialize charCount
			charCount = 0;

			// loop through each char in the line
			for ( count = 3; count < (int)strlen( lineBuffer ); count++ )
			{
				
				// if we are reading part of a float coordinate
				if ( ( lineBuffer[count] == '-' ) || ( isdigit( lineBuffer[count] ) ) || ( lineBuffer[count] == '.') )
				{
					// store this char into temp
					temp[charCount++] = lineBuffer[count];
				}

				// if we are not reading part of a float and a float exists in temp
				else if ( charCount != 0 )
				{
					// copy the float coordinate to tempFloat
					strncpy( tempFloat, temp, charCount );

					//
					tempFloat[ charCount ] = '\n';

					// store the coordinate in our normals array
					coordinate = atof( tempFloat );
					normals[normalIndex++] = coordinate;

					// re-initialize charCount
					charCount = 0;
				}
			}
		}

		// if we are reading face info
		if ( strncmp( lineBuffer, "f ", 2 ) == 0 )
		{

			// initialize charCount, isVertex and isFirstNormal
			charCount = 0;
			isVertex = 1;
			isFirstNormal = 1;

			// loop through each char in the line
			for ( count = 2; count < (int)strlen( lineBuffer ); count++ )
			{
				
				// if we are reading part of an index
				if ( isdigit( lineBuffer[count] ) )
				{
					// store this char into temp
					temp[charCount++] = lineBuffer[count];
				}

				// if we are not reading part of an index and an index exists in temp
				else if ( charCount != 0 )
				{

					// if the index is a vertex
					if ( isVertex == 1 )
					{

						// copy the float coordinate to tempFloat
						strncpy( tempFloat, temp, charCount );

						//
						tempFloat[ charCount ] = '\n';

						// store the coordinate in our indices array
						index = atof( tempFloat );
						elements[elementIndex++] = (int)index;
					}

					// if the index is a normal
					else
					{

						// if this is the first normal in the line
						if ( isFirstNormal == 1 )
						{
							// copy the float coordinate to tempFloat
							strncpy( tempFloat, temp, charCount );

							//
							tempFloat[ charCount ] = '\n';

							// store the coordinate in our normals array
							index = atof( tempFloat );
							elements[elementIndex++] = (int)index;

							// switch isFirstNormal
							isFirstNormal *= -1;
						}
					}

					// switch isVertex
					isVertex *= -1;

					// re-initialize charCount
					charCount = 0;
				}
			}
		}

	}

	// close file
	fclose( objFile );

	// return ok
	return 1;
}

 

 

my draw routine:

// draw our model
	glBegin( GL_TRIANGLES );

	// go through each element
	for ( i = 0; i < elementIndex; i += 4 )
	{
		// set offsets
		normalOffset  = 3;
		vertexOffset = 3;

		// calculate index of x coordinate of current normal
		currentNormalIndex = normalOffset * ( indices[i + 1] - 1 );

		// calculate index of x coordinates of the three vertices
		firstVertexIndex = vertexOffset * ( indices[ i + 1 ] - 1 );
		secondVertexIndex = vertexOffset * ( indices[ i + 2 ] - 1 );
		thirdVertexIndex = vertexOffset * ( indices[ i + 3 ] - 1 );

		// set the normal for our triangle face
		glNormal3f( normals[ normalOffset ], 
			normals[ normalOffset + 1 ], 
			normals[ normalOffset + 2 ] );

		// set vertex 1
		glVertex3f( vertices[ firstVertexIndex ], 
			vertices[ firstVertexIndex + 1 ],
			vertices[ firstVertexIndex + 2 ]);

		// set vertex 2
		glVertex3f( vertices[ secondVertexIndex ], 
			vertices[ secondVertexIndex + 1 ],
			vertices[ secondVertexIndex + 2 ]);
		
		// set vertex 3
		glVertex3f( vertices[ thirdVertexIndex ], 
			vertices[ thirdVertexIndex + 1 ],
			vertices[ thirdVertexIndex + 2 ]);

	}
	glEnd();

 

 

The object was exported from blender using:

  • selection only (current model)
  • include normals
  • triangulate faces
  • keep vertex order

I understand that there are alternative ways to import and draw an .obj file but this will help me understand OpenGL and 3D objects better since I'm new to both 3D modelling and OpenGL.

 

Can someone help through this?

 

arigatou

 

EDIT: the indices are stored like this: [vector], [vector normal], [vector], [vector] for each line and I use the same vector normal for the 3 vectors to save space

Edited by hikarihe

Share this post


Link to post
Share on other sites
SimonForsman    7642


thanks ^^ it works. my mistake. should I delete the post?

hi, how did you fix it pls? I have a similar issue


as lspiro said, the indices are 1 based in obj files, in C and C++ (and quite many other languages aswell) arrays start at 0, so instead of:
glVertex3f( vertices[ firstVertexIndex ],
vertices[ firstVertexIndex + 1 ],
vertices[ firstVertexIndex + 2 ]);

you do:
glVertex3f( vertices[ firstVertexIndex -1 ],
vertices[ firstVertexIndex ],
vertices[ firstVertexIndex + 1 ]);

(if you use vertex arrays or VBOs you do the equivalent operation where you initialize your array/vbo instead)

Share this post


Link to post
Share on other sites
hikarihe    243

thanks ^^ it works. my mistake. should I delete the post?

hi, how did you fix it pls? I have a similar issue

 

 

       // calculate index of x coordinate of current normal
        currentNormalIndex = normalOffset * ( indices[i + 1] - 1 ); 

        // calculate index of x coordinates of the three vertices
        firstVertexIndex = vertexOffset * ( indices[ i + 1 ] - 1 ); <<<<< here, replace with ( indices[ i ] - 1 )
        secondVertexIndex = vertexOffset * ( indices[ i + 2 ] - 1 );
        thirdVertexIndex = vertexOffset * ( indices[ i + 3 ] - 1 );

 

that's it. rest of the code is fine, but could be cleaned up ^ ^'

Share this post


Link to post
Share on other sites
hikarihe    243

 

thanks ^^ it works. my mistake. should I delete the post?

hi, how did you fix it pls? I have a similar issue

 

as lspiro said, the indices are 1 based in obj files, in C and C++ (and quite many other languages aswell) arrays start at 0, so instead of:
glVertex3f( vertices[ firstVertexIndex ],
vertices[ firstVertexIndex + 1 ],
vertices[ firstVertexIndex + 2 ]);

you do:
glVertex3f( vertices[ firstVertexIndex -1 ],
vertices[ firstVertexIndex ],
vertices[ firstVertexIndex + 1 ]);

(if you use vertex arrays or VBOs you do the equivalent operation where you initialize your array/vbo instead)

 

You can go to the root of the problem instead and do -1 when storing:

 

Store indices:

// if the index is a normal
else
{

	// increment currentNormal
	currentNormal++;

	// if this is the third normal in the line
	if ( currentNormal == 3 )
	{
		// copy the float coordinate to tempFloat
		strncpy_s( tempFloat, 16, temp, charCount );

		//
		tempFloat[ charCount ] = '\n';

		// store the coordinate in indices array
		index = atoi( tempFloat );
		elements[(*elementIndex)++] = index - 1;

		// set current normal to 0
		currentNormal = 0;
	}
} 

 

 

Draw:

// calculate index of x coordinate of current normal
currentNormalIndex = normalOffset * ( indices[i + 3] );

// calculate index of x coordinates of the three vertices
firstVertexIndex = vertexOffset * ( indices[ i ] );
secondVertexIndex = vertexOffset * ( indices[ i + 1 ] );
thirdVertexIndex = vertexOffset * ( indices[ i + 2 ] );

 

looks much cleaner! ^w^

Share this post


Link to post
Share on other sites
jumz    117

Hi,

I am trying to import chess pieces from 3dsmax to opengl.

However, I am quite new to opengl and it has been a big challenge so far.

Any help will be appreciated?

Share this post


Link to post
Share on other sites
blueshogun96    2264

Hi,

I am trying to import chess pieces from 3dsmax to opengl.

However, I am quite new to opengl and it has been a big challenge so far.

Any help will be appreciated?

 

I recommend starting a new thread for this question, then it can get more specific attention.

 

I think the proper word you want to use is "export".  Export your 3D model to a 3D format that's well documented such as collada (.dae), object (.obj), .3ds, etc.  I don't have 3dsmax so I don't know what types of exports it supports; I use Blender.  Depending on the format you choose to export, you may have to write your own loader for the file and parse it manually, then format the vertex data into a compatible format that OpenGL can use.

 

The answer to your question is not a simple one.  Do you have a specific export format in mind?  And how far with OpenGL have you gotten already?  You may be biting off more than you can chew; I'm asking because I don't quite understand what is so difficult for you.

 

Shogun.

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++.
      Question:
      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