PDA

View Full Version : glDrawElements vs. looping with glVertex



qiau
01-06-2007, 03:47 PM
Hi, just started with opengl (using perl, SDL) and ran into a problem.

I'm porting a .3DS-reader from C++ to perl and have some problems with the model drawing.

In the C++ code the draw uses glDrawElements and I really can't get it to work at all. But when I loop and use glVertex instead it works fine (but is really, really slow). This might be a perl (SDL::OpenGL) specific problem but you might have some answers anyway. Since I just started out with opengl it could be something really trivial..

The non-working code looks like this:

glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, 0, $normals);
glVertexPointer(3, GL_FLOAT, 0, $vertexes);

for($i=0; $i < $object->{numfaces}; $j++) {
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, $object->{material});
glDrawElements(GL_TRIANGLES, $object->{numsubfaces}, GL_UNSIGNED_SHORT, $object->{subfaces});
}And the working and really slow one:

glBegin(GL_TRIANGLES);
glColor(1,1,1);
for($z=0; $z < $object->{numsubfaces}, $z++) {
$vertex = $object->{subfaces}[$z]*3;

$x = $object->{vertexes}[$vertex];
$y = $object->{vertexes}[$vertex+1];
$z = $object->{vertexes}[$vertex+2];

glVertex($x, $y, $z);
}
glEnd();I thought those two code-strips did the same thing but obviously not.

songho
01-07-2007, 08:23 PM
qiau,
I think your index array may be wrong. It looks to me that $object->(subspaces) is 3 times larger than it should be. The index array stores the indices of vertices. (Is it the index array, isn't it?)

For example, if you have a triangle, and then you will have 3 vertex coords in your vertex array; (x,y,z),(x,y,z),(x,y,z). So, total 9 float values are in the vertex array. But the index array contains only 3 entries; 0, 1, 2.

I may be just confused about your variable names, but the second param of glDrawElements() is the number of indices to be used, not the number of faces.

And, please add glEnableClientState(GL_NORMAL_ARRAY) before calling glNormalPointer().

qiau
01-08-2007, 02:09 AM
Oh, you'r right. I can't give it a try right now since I'm at work and didn't bring the code here (a rather good idea, otherwise it would be a little bit too much opengl and no work :) ).

When I read your reply and the code again what you say makes sense. I thought the second argument to glDrawElements was how many to draw of the first argument (triangle, 3 vertexes).

I'll have to try it out when I get home and straight out the variable names too, they are pretty confusing right now :) .

Anyway, the performance-issue is solved anyway (with drawlists, of couse..). I learn a loads of stuff every day that offen explains yesterdays problems, I'm pretty much in love with opengl.

Thanks a lot for your answer!