STL Mesh Rendering

Started by
11 comments, last by scap3y 11 years, 5 months ago
Hey All,

I want to render a mesh which is stored in the .STL format (a small part of the file is given below) and control it via interactions from the mouse.

solid 20110519125647
facet normal -0.334931 -0.236570 -0.912061
outer loop
vertex 10.481026 1.232170 4.632938
vertex 10.542211 1.232170 4.610470
vertex 10.542211 1.145546 4.632938
endloop
endfacet

facet normal -0.174629 -0.346906 -0.921499
outer loop
vertex 10.669180 1.030518 4.632938
vertex 10.743861 1.030518 4.618786
vertex 10.743861 0.992924 4.632938
endloop
endfacet

facet normal -0.117726 -0.352012 -0.928562
outer loop
vertex 10.844687 0.959465 4.632938
vertex 10.743861 1.030518 4.618786
vertex 10.844687 1.030518 4.606003
endloop
endfacet


Now, this continues to about 80,000 to 140,000 faces, depending on the file. I have written a basic program to read these meshes using fopen but it is very inefficient (takes more than 10 min for the smallest files). I have also implemented a custom ArcBall which works on any geometry after it has been rendered.

It would be really nice if someone can give me a better way to handle these files.
Advertisement
First up, what is your current code doing? Have you profiled to determine where the bottleneck is? Is it possible to post the loading code in a stand alone manner?
If the problem is with excessive calls to fopen() with small read sizes, try refactoring so that the whole file (or a large chunk of it) is read to memory at one go, and parsing occurs to data residing in memory.

First up, what is your current code doing? Have you profiled to determine where the bottleneck is? Is it possible to post the loading code in a stand alone manner?

Sure, this the code I am using..
[source lang="cpp"]#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include <math.h>

GLfloat lightPos[] = {-300.0f, 100.0f, 100.0f, 0.0f };

// Define a constant for the value of PI
#define GL_PI 3.1415f

// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

float vertex[3][3];
# include &lt; stdio.h&gt;
# include &lt; stdlib.h&gt;
# include &lt; string.h&gt;

struct group // Define a group which will take in the normal and vertices from the .stl files
{
float normal[3];
float vertex1[3];
float vertex2[3];
float vertex3[3];
char unuse [2];
};

struct group facet[500000] ;

int i,j,num;

char filename[80];
int numfacet[1];

// Reduces a normal vector specified as a set of three coordinates,
// to a unit normal vector of length one.
void ReduceToUnit(float vector[3])
{
float length;

// Calculate the length of the vector
length = (float)sqrt((vector[0]*vector[0]) +
(vector[1]*vector[1]) +
(vector[2]*vector[2]));

// Keep the program from blowing up by providing an exceptable
// value for vectors that may calculated too close to zero.
if(length == 0.0f)
length = 1.0f;

// Dividing each element by the length will result in a
// unit normal vector.
vector[0] /= length;
vector[1] /= length;
vector[2] /= length;
}

// Points p1, p2, & p3 specified in counter clock-wise order
void calcNormal(struct group *facet, float out[3])
{
float v1[3],v2[3];
static const int x = 0;
static const int y = 1;
static const int z = 2;

// Calculate two vectors from the three points
v1[x] = (*facet).vertex1[x] -(*facet).vertex2[x];
v1[y] = (*facet).vertex1[y] - (*facet).vertex2[y];
v1[z] = (*facet).vertex1[z] - (*facet).vertex2[z];

v2[x] = (*facet).vertex2[x] - (*facet).vertex3[x];
v2[y] = (*facet).vertex2[y] - (*facet).vertex3[y];
v2[z] = (*facet).vertex2[z] - (*facet).vertex3[z];

// Take the cross product of the two vectors to get
// the normal vector which will be stored in out
out[x] = v1[y]*v2[z] - v1[z]*v2[y];
out[y] = v1[z]*v2[x] - v1[x]*v2[z];
out[z] = v1[x]*v2[y] - v1[y]*v2[x];

// Normalize the vector (shorten length to one)
ReduceToUnit(out);
}


// Called to draw scene
void RenderScene(void)
{
float normal[3];

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

//glTranslatef(0.0f,0.0f,-500.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glTranslatef(-2.5,0.0,0.0);
glPushMatrix();

glRotatef(xRot,1,0,0);
glRotatef(yRot,0,1,0);

glColor3ub(128, 128, 128);
glBegin(GL_TRIANGLES);
{
for(j=0;j&lt;num;j++)
{
facet[j].vertex1;
facet[j].vertex2;
facet[j].vertex3;

//float v[3][3]={ facet[j].vertexs[3][3]};

calcNormal(&facet[j],normal);
glNormal3fv(normal);
glVertex3fv(facet[j].vertex1);
glVertex3fv(facet[j].vertex2);
glVertex3fv(facet[j].vertex3);
}
}
glEnd();

glPopMatrix();
glutSwapBuffers();
}

// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLfloat ambient[]={ 0.6f,0.6f,0.7f,1.0f};
GLfloat diffuse[]={0.7f,0.7f,0.7f,1.0f};
GLfloat spec[]={1.0f,1.0f,1.0f,1.0f};
GLfloat specma[]={1.0f,1.0f,1.0f,1.0f};


// Light values and coordinates
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet

// Enable lighting

glEnable(GL_LIGHTING);

// Setup and enable light 0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuse);
glLightfv(GL_LIGHT0,GL_SPECULAR,spec);

// Enable color tracking

glEnable(GL_LIGHT0);
// Set Material properties to follow glColor values
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT,GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT,GL_SPECULAR,specma);
glMateriali(GL_FRONT,GL_SHININESS,128);


// Light blue background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
}

/*
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;

if(key == GLUT_KEY_DOWN)
xRot += 5.0f;

if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;

if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;

//if(key &gt; 356.0f)
// xRot = 0.0f;

//if(key &lt; -1.0f)
// xRot = 355.0f;

// if(key &gt; 356.0f)
// yRot = 0.0f;

// if(key &lt; -1.0f)
// yRot = 355.0f;

// Refresh the Window
glutPostRedisplay();
}
*/

void ChangeSize(int w, int h)
{
//
GLfloat nRange = 3.0f;

/*

GLfloat aspect;
aspect = (GLfloat)w/(GLfloat)h;

glViewport(0,0,w,h);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();


gluPerspective(1000.0f,aspect,1.0,1000.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
*/

// Prevent a divide by zero
if(h == 0)
h = 1;

// Set Viewport to window dimensions
glViewport(0, 0, w, h);

// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Establish clipping volume (left, right, bottom, top, near, far)
if (w &lt;= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, 2.0*(-nRange), 2.0*(nRange));
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, 2.0*(-nRange), 2.0*(nRange));

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glLightfv(GL_LIGHT0,GL_POSITION,lightPos);

}

int main(int argc, char* argv[])
{
//stl loader

FILE *binary;
//FILE *out;

if( (binary =fopen("Desktop\\QCAN_1-3-12-2-1107-5-4-7-8501-30000011050313402896800000046_20110519135647.stl","rb"))==NULL )////stl file location
{
printf("\nThe file could not be accessed. Are you sure of the location..?\n");
exit(1);
}

//out = fopen("C:\\my documents\\stlexperi3.txt","w");

fread(filename,sizeof(char),80,binary) ;
fread(numfacet,sizeof(int),1,binary);

num=numfacet[0];

for (j=0;j&lt;num;j++)
{
fread(facet[j].normal,sizeof(float),3,binary);
fread(facet[j].vertex1,sizeof(float),3,binary);
fread(facet[j].vertex2,sizeof(float),3,binary);
fread(facet[j].vertex3,sizeof(float),3,binary);
fread(facet[j].unuse,sizeof(char),2,binary);
}

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500,500);
// glutCreateWindow("Lighted Jet");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();

return 0;
}[/source]

If the problem is with excessive calls to fopen() with small read sizes, try refactoring so that the whole file (or a large chunk of it) is read to memory at one go, and parsing occurs to data residing in memory.


Very sorry, I am not exactly sure how to do that.. mellow.png

Very sorry, I am not exactly sure how to do that..
[/quote]
Instead of directly reading little chunks from the file pointer, read a large amount of data into a intermediate buffer, and then use memory operations like memcpy instead of fread and sscanf rather than scanf.


Sure, this the code I am using..
[/quote]

I'm confused. The file in your original post looks like some kind of text format. Your code appears to be trying to treat it as binary data. Have you pre-processed / compiled the file into a binary format?

If not, your code simply won't work. Your program will try to interpret the textual data as numeric, which will have very unexpected results. For example, one possibility is that the "numfacet" value is being incorrectly interpreted as a very high number, and your loop takes a very long time to complete. Try using your debugger to discover the value of "num" in your loop. On my system, trying the first few lines of your code gives a value of "808,525,944" for "num".

Regardless of whether the file is binary or text, you need to have a lot more error checking. Every call to fread() or scanf() should be testing the return value to ensure it is as you expect.

You might want to start with something like this first:

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


struct Vertex {
float coords[3];
};

struct Facet {
struct Vertex normal;
struct Vertex vertices[3];
};


void complain_and_exit(const char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}

int main(int argc, char* argv[]) {
FILE *file = fopen("test.stl","r");
if(!file) {
complain_and_exit("The file could not be accessed. Are you sure of the location..?");
}

int count;
if(fscanf(file, "solid %d\n", &count) != 1) {
complain_and_exit("Failed to read header");
}
printf("Expecting %d facets\n", count);

int i;
for(i = 0 ; i < count ;++i) {
struct Facet facet;

if(fscanf(file, "facet normal %f %f %f\n", &facet.normal.coords[0], &facet.normal.coords[1], &facet.normal.coords[2]) != 3) {
complain_and_exit("Failed to read facet normal");
}
printf("Facets[%d] normal (%f, %f, %f)\n", i, facet.normal.coords[0], facet.normal.coords[1], facet.normal.coords[2]);

if(fscanf(file, "outer loop\n") != 0) {
complain_and_exit("Failed to read \'outer loop\'");
}

int j;
for(j = 0 ; j < 3 ; ++j) {
struct Vertex *vertex = &facet.vertices[j];

if(fscanf(file, "vertex %f %f %f\n", &vertex->coords[0], &vertex->coords[1], &vertex->coords[2]) != 3) {
complain_and_exit("Failed to read vertex");
}
printf("Facets[%d] vertex[%d] (%f, %f, %f)\n", i, j, vertex->coords[0], vertex->coords[1], vertex->coords[2]);
}

if(fscanf(file, "endloop\n") != 0) {
complain_and_exit("Failed to read \'endloop\'");
}

if(fscanf(file, "endfacet\n") != 0) {
complain_and_exit("Failed to read \'endfacet\'");
}
}
fclose(file);
}

When you have it working, then we can see if it needs optimisation.

Also, while you're testing your program, try to start with a simpler mesh. For example, try to load a cube. This will be easier to verify and quicker to load.

I'm confused. The file in your original post looks like some kind of text format. Your code appears to be trying to treat it as binary data. Have you pre-processed / compiled the file into a binary format?


The data type is ASCII STL. I will run the code you have given and update asap. Thanks. smile.png
Please note that the code is for reference. I am not familiar with the file format.

Skimming the wikipedia entry you linked to, my code is incorrect as it attempts to interpret the a(apparently optional) name of a mesh as a number, this was based on what your code appeared to be doing. Looking further, your code seems to be trying to implement the Binary STL format. It appears that your exported default to naming the mesh with some kind of timestamp.

Thus my code would incorrectly attempt to parse this timestamp as a number, when in fact the timestamp is larger than can be represented with a 32 bit unsigned integer.
I actually tried attaching a part of the file here but the attachement plugin wouldn't let me do it. I didn't know that the input formats for Binary and ASCII STLs were different..

In any case, the name of the mesh is irrelevant, right..? I mean, as long the normals and vertices can be read, they will be rendered, right..? huh.png

I have found extensive software packages that do a lot of stuff (Assimp, VTK, etc).. But they are way too complicated and just increase the dependencies of my code. I would prefer to have something much simpler.. wacko.png blink.png
Maybe simpler to learn and integrate a 3rd party API (Assimp etc) rather than learn how to parse file formats from scratch. At least consider it one more good time before continuing. Both paths will be beneficial to your learning.

This topic is closed to new replies.

Advertisement