• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
scap3y

STL Mesh Rendering

12 posts in this topic

Hey All,

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

[i][b]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[/b][/i]
[i][b]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[/b][/i]
[i][b]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[/b][/i]

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 [b]fopen[/b] 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.
0

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1351596964' post='4995360']
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?
[/quote]
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] Edited by scap3y
0

Share this post


Link to post
Share on other sites
[quote name='clb' timestamp='1351597520' post='4995364']
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.
[/quote]

Very sorry, I am not exactly sure how to do that.. [img]http://public.gamedev.net//public/style_emoticons/default/mellow.png[/img]
0

Share this post


Link to post
Share on other sites
[quote]
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.

[quote]
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:
[code]
#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);
}
[/code]
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. Edited by rip-off
1

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1351601358' post='4995382']
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?
[/quote]

The data type is [url="http://en.wikipedia.org/wiki/STL_%28file_format%29#ASCII_STL"]ASCII STL[/url]. I will run the code you have given and update asap. Thanks. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] Edited by scap3y
0

Share this post


Link to post
Share on other sites
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 [url="http://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL"]Binary STL[/url] 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.
0

Share this post


Link to post
Share on other sites
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..? [img]http://public.gamedev.net//public/style_emoticons/default/huh.png[/img]

I have found extensive software packages that do a lot of stuff ([url="http://assimp.sourceforge.net/lib_html/index.html"]Assimp[/url], [url="http://vtk.org/"]VTK[/url], etc).. But they are way too complicated and just increase the dependencies of my code. I would prefer to have something much simpler.. [img]http://public.gamedev.net//public/style_emoticons/default/wacko.png[/img] [img]http://public.gamedev.net//public/style_emoticons/default/blink.png[/img]
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
[quote name='achild' timestamp='1351607540' post='4995429']
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.
[/quote]
Okay, thanks.
0

Share this post


Link to post
Share on other sites
Does anyone have any references to documentation regarding [url="http://assimp.sourceforge.net/lib_html/index.html"]Assimp[/url]..? I have been trying since the past week and I haven't been able to even get the importer to fire up.. The documentation given in the site of the source code isn't very comprehensive and the sample codes just do not work. :(
0

Share this post


Link to post
Share on other sites
So, I have tried for the past week without any luck with Assimp (no proper documentation, etc) and I have implemented a pretty efficient STL Rendering system using VTK. If there are any updates/changes, I will probably update it in the VTK forum (since now it has become completely unrelated to NeHe). [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

To everyone who replied - thank you. [img]http://public.gamedev.net//public/style_emoticons/default/cool.png[/img]
0

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  
Followers 0