Sign in to follow this  
Adam West

OpenGL lib3ds and texture mapping?

Recommended Posts

Adam West    219
hello again!

i have fixed up a few problems on my 3ds loader using lib3ds, my only problem now is that i have no idea how to load a texture map onto the loaded model. do i have to use lib3ds Material or something like that?

3ds.h
[CODE]

#include "main.h"
#include "lib3ds/file.h"
#include "lib3ds/mesh.h"
#include "lib3ds/material.h"

class Object
{
public:
Object(const char* filename);
virtual ~Object();
virtual void Draw() const;
virtual void CreateVBO();
void applyTexture(const char*texfilename);

protected:
void GetFaces();
unsigned int m_TotalFaces;
Lib3dsFile * m_model;

Lib3dsMesh* Mesh;
GLuint textureObject;
GLuint m_VertexVBO, m_NormalVBO, m_TexCoordVBO;
};
[/CODE]

3ds.cpp
[CODE]
#include "3dsloader.h"
#include "shader.h"

Object::Object(const char* filename)
{
m_TotalFaces = 0;
m_model = lib3ds_file_load(filename);
// If loading the model failed, we throw an exception
if(!m_model)
{
cout << ("Unable to load ", filename);
}
Lib3dsMesh* mesh = lib3ds_file_mesh_by_name(m_model,"filename");


}
Object::~Object()
{
if(m_model) // if the file isn't freed yet
lib3ds_file_free(m_model); //free up memory
}

void Object::GetFaces()
{
m_TotalFaces = 0;
Lib3dsMesh * mesh;
// Loop through every mesh.
for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next)
{
// Add the number of faces this mesh has to the total number of faces.
m_TotalFaces += mesh->faces;
}
}
void Object::CreateVBO()
{
assert(m_model != NULL);
// Calculate the number of faces we have in total
GetFaces();
// Allocate memory for our vertices and normals
Lib3dsVector * vertices = new Lib3dsVector[m_TotalFaces * 3];
Lib3dsVector * normals = new Lib3dsVector[m_TotalFaces * 3];
Lib3dsTexel* texCoords = new Lib3dsTexel[m_TotalFaces * 3];

Lib3dsMesh * mesh;
unsigned int FinishedFaces = 0;
// Loop through all the meshes
for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next)
{

lib3ds_mesh_calculate_normals(mesh, &normals[FinishedFaces*3]);
// Loop through every face
for(unsigned int cur_face = 0; cur_face < mesh->faces;cur_face++)
{

Lib3dsFace * face = &mesh->faceL[cur_face];
for(unsigned int i = 0;i < 3;i++)
{

if(mesh->texels)
{
memcpy(&texCoords[FinishedFaces*2 + i], mesh->texelL[face->points[ i ]], sizeof(Lib3dsTexel));
}
memcpy(&vertices[FinishedFaces*3 + i], mesh->pointL[face->points[ i ]].pos, sizeof(Lib3dsVector));

}

FinishedFaces++;
}

}

// Generate a Vertex Buffer Object and store it with our vertices
glGenBuffers(1, &m_VertexVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, vertices, GL_STATIC_DRAW);
// Generate another Vertex Buffer Object and store the normals in it
glGenBuffers(1, &m_NormalVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, normals, GL_STATIC_DRAW);
// Generate a third VBO and store the texture coordinates in it.
glGenBuffers(1, &m_TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsTexel) * 3 * m_TotalFaces, texCoords, GL_STATIC_DRAW);

// Clean up our allocated memory
delete vertices;
delete normals;
delete texCoords;

// We no longer need lib3ds
lib3ds_file_free(m_model);
m_model = NULL;
}
void Object::applyTexture(const char*texfilename)
{

textureObject = SOIL_load_OGL_texture(texfilename,SOIL_LOAD_AUTO,SOIL_CREATE_NEW_ID,SOIL_FLAG_MIPMAPS);

glBindTexture(GL_TEXTURE_2D,textureObject);// use our newest texture
}

void Object::Draw() const
{



// Enable vertex, normal and texture-coordinate arrays.
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);



// Bind the VBO with the normals.
glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO);
// The pointer for the normals is NULL which means that OpenGL will use the currently bound VBO.
glNormalPointer(GL_FLOAT, 0, NULL);

glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO);
glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO);
glVertexPointer(3, GL_FLOAT, 0, NULL);
// Render the triangles.
glDrawArrays(GL_TRIANGLES, 0, m_TotalFaces * 3);


glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
[/CODE]

at the moment all of the texture co-ordinates are messed up, it looks like this:

[URL=http://www.leethacker.com/][IMG]http://www.leethacker.com/images/fpo2wxb3zlp6bpgvt3wk.png[/IMG][/URL]

the output should actually be a perfectly mapped pyramid with no black parts

Share this post


Link to post
Share on other sites
the_visualist    188
Just create a simple plane model, save it as .3ds and load it. Then see at which point the texture coordinates get messed up. It should be 0/0, 0/1, 1/1 etc. when you load it.
If you want to save yourself a lot of time, then forget about 3ds, its lacking things in too many ways. Try .obj for a simple format that also supports bigger meshes. Its also very easy to create your own loader for it.

Share this post


Link to post
Share on other sites
f1af    100
number of tex coord not equal numer of face. if tex coord on neighboring face is equal - both face has one texcoord.
for example, if you have default cube-object, you have 24 faces, but 8 vertexes and 8 texcoord.


[CODE]
1,1 | | 1,1
0,0 0,1 | | 0,1 0,0
-------------- --------------
[/CODE]


this two face have 3 tex coord. not 6. 3 on both. somsing like that...

Share this post


Link to post
Share on other sites
Adam West    219
[quote name='f1af' timestamp='1334574010' post='4931684']
number of tex coord not equal numer of face. if tex coord on neighboring face is equal - both face has one texcoord.
for example, if you have default cube-object, you have 24 faces, but 8 vertexes and 8 texcoord.


[CODE]
1,1 | | 1,1
0,0 0,1 | | 0,1 0,0
-------------- --------------
[/CODE]


this two face have 3 tex coord. not 6. 3 on both. somsing like that...
[/quote]



could you modify my code so it makes more sense. this could help me and many other people with this problem?

Share this post


Link to post
Share on other sites
f1af    100
it uogly, in the future I fix it function. but if call this function after load 3ds, tex coord will by fixed.

[CODE]
void WorkBase::vertexNoDifTexCoordExtract( SPtr<BaseMesh> baseMesh ) const
{
SPtr<BaseSide> sptrSide;
SPtr<BaseAI> sptrBaseAI;
uint indexCount, indexOfVertex, pointCount = baseMesh->point()->count() / 8;

char doneIndex[pointCount];
memset( doneIndex, 0, pointCount*sizeof( char ) );

for ( uint i = 0; baseMesh->side()->next( &i, &sptrSide ); )
{
for ( uint j = 0; sptrSide->arrayIndex()->next( &j, &sptrBaseAI ); )
{
indexCount = sptrBaseAI->index()->count();

if (indexCount>64000) continue;

for ( uint n = 0; n < indexCount; n++ )
{
indexOfVertex = *sptrBaseAI->index()->atRo( n );

if ( !doneIndex[indexOfVertex] ) doneIndex[indexOfVertex] = 1;
else
{
for ( uint m = 0; m < 8; m++ )
{
if (( indexOfVertex*8 + m ) < baseMesh->point()->count() ) // TODO kastil', need normal fix
{
float varFloat = *baseMesh->point()->atRo( indexOfVertex * 8 + m );
baseMesh->point()->appendVar( varFloat );
}
}

*sptrBaseAI->index()->atRw( n ) = baseMesh->point()->count() / 8 - 1;
}
}
}
}

}
[/CODE]

AI - its Array Indexes.

If u intresting, if u need, I can give my code of load 3ds. Its class, inherit from some python-3ds-module-source-code, not lib3ds. In the future I wont use lib3ds. But now.. my uogly, but working code:


[CODE]

#include "drawlib/scene/loader_3ds.h"

#include "drawlib/scene/scene_manager.h"


namespace drawlib
{


Loader3DS::Loader3DS( SceneManager *sceneManager )
{
m_sceneManager = sceneManager;
m_forStreamSteckStart = 0;
m_forStreamSteckEnd = 0;
m_wasError = false;
setIsSimple( false );
reset();
}


Loader3DS::~Loader3DS()
{
}


void Loader3DS::P_updatePersent()
{
int persent = 1 + (( 100 * m_currentFileDevice->at() ) / m_currentFileDevice->size() );

if ( m_sceneManager->jobManager()->isThreadOn() )
setProgress( persent );
}


void Loader3DS::setWasErrorToFalse()
{
m_wasError = false;
}


bool Loader3DS::getWasError() const
{
return m_wasError;
}


void Loader3DS::load( SPtr<BaseMesh> baseMesh, QString fileName, QString *nameObject )
{
if ( nameObject ) *nameObject = "3ds";

m_sceneManager->storer()->mesh()->setHide( baseMesh, true );

m_listForStreamBaseMesh.append( baseMesh );
m_listForStreamFileName.append( fileName );

m_sceneManager->jobManager()->doRun( this );
}


void Loader3DS::reset()
{
JobThread::reset();

// m_sceneManager=0; - not need

m_baseAI.reset();
m_baseSide.reset();
m_baseMaterial.reset();
m_baseMesh.reset();

m_baseAIMaterial.reset();
m_baseSideMaterial.reset();

m_fileName = QString::null;
m_pathToFile = QString::null;
m_mapMaterial.clear();

m_indexOffset = 0;
m_version = 0;
m_count_mapUV = 0;

if ( m_forStreamSteckStart == m_forStreamSteckEnd )
{
m_forStreamSteckStart = 0;
m_forStreamSteckEnd = 0;
m_listForStreamBaseMesh.clear();
m_listForStreamFileName.clear();
}
}



/**************************************************************
************************ for QThread *************************
*************************************************************/

void Loader3DS::startJob()
{
m_baseMesh = *m_listForStreamBaseMesh.at( m_forStreamSteckStart );
m_fileName = *m_listForStreamFileName.at( m_forStreamSteckStart );
m_forStreamSteckStart++;

setName( "load: \"" + QFileInfo( m_fileName ).fileName() + "\"" );

m_baseMesh->reset();
m_pathToFile = QFileInfo( m_fileName ).dirPath();
// m_baseMesh->point()->setBlokSize( 250000 );

if ( !ProcessFile( m_fileName.latin1() ) ) m_wasError = true;

if ( m_version != 3 ) m_wasError = true;
}


void Loader3DS::endJob()
{
m_baseMesh = *m_listForStreamBaseMesh.at( m_forStreamSteckEnd );
m_forStreamSteckEnd++;

m_sceneManager->workBase()->vertexNoDifTexCoordExtract( m_baseMesh );
m_sceneManager->workBase()->normalize( m_baseMesh );

m_baseMesh->update();
uint textureId = 0;
QValueList<uint> filter;

for ( uint i = 0; m_baseMesh->side()->next( &i, &m_baseSide ); )
{
if ( !m_baseSide->getMaterialId() ) continue;

m_baseMaterial = m_sceneManager->storer()->material()->idToSPtr( m_baseSide->getMaterialId() );
textureId = m_baseMaterial->getTextureId();

if ( !textureId ) continue;

if ( filter.find( textureId ) != filter.end() ) continue;
else filter.append( textureId );

m_sceneManager->storer()->texture()->idToSPtr( textureId )->update();
}

m_sceneManager->storer()->mesh()->setHide( m_baseMesh, false );
reset();
}



/**************************************************************
********************* Check correct 3ds **********************
*************************************************************/

bool Loader3DS::UserVersion( uint version )
{
m_version = version;

if ( m_version != 3 ) return false;

return true;
}



/**************************************************************
*********************** Material list ************************
*************************************************************/

void Loader3DS::UserMatName( const string name )
{
uint id;
BaseMaterial *baseMaterial;
m_sceneManager->storer()->material()->create( baseMaterial, id );
m_baseMaterial.set( baseMaterial );
m_mapMaterial[name] = id;
}


void Loader3DS::UserMatColor( float c0, float c1, float c2, int flag )
{
if ( flag == 1 ) m_baseMaterial->color()->setColor( c0 / 1.4f, c1 / 1.4f, c2 / 1.4f );
else if ( flag == 2 ) m_baseMaterial->color()->setColorAmbient( c0, c1, c2 );
else m_baseMaterial->color()->setColorSpecular( c0, c1, c2 );
}


void Loader3DS::UserMapFile( const string fileName )
{
uint textureId;
BaseTexture *baseTexture;
SPtr<BaseTexture> baseTextureSPtr;

m_sceneManager->storer()->texture()->create( baseTexture, textureId );
baseTextureSPtr.set( baseTexture );

if ( m_sceneManager->loaderImage()->load( baseTextureSPtr,
m_pathToFile + "/" + QString( fileName ).lower() ) )
m_baseMaterial->setTextureId( textureId );

p_updatePersent();
}



/**************************************************************
*************************** Vertex ***************************
*************************************************************/

void Loader3DS::User3dVertCount( unsigned short count )
{
count = 0;
m_indexOffset = m_baseMesh->point()->count() / 8;
m_count_mapUV = 0;

p_updatePersent();
}


void Loader3DS::User3dVert( float x, float y, float z )
{
m_baseMesh->point()->appendVar( 0 );
m_baseMesh->point()->appendVar( 0 );

m_baseMesh->point()->appendVar( 0 );
m_baseMesh->point()->appendVar( 0 );
m_baseMesh->point()->appendVar( 0 );

m_baseMesh->point()->appendVar( x );
m_baseMesh->point()->appendVar( y );
m_baseMesh->point()->appendVar( z );
}


void Loader3DS::UserMapVertex( float u, float v )
{
*m_baseMesh->point()->atRw(( m_indexOffset + m_count_mapUV )*8 + 0 ) = u;
*m_baseMesh->point()->atRw(( m_indexOffset + m_count_mapUV )*8 + 1 ) = v;
m_count_mapUV++;
}



/**************************************************************
*************************** Index ****************************
*************************************************************/

void Loader3DS::User3dFaceCount( unsigned short )
{
m_baseSide = m_baseMesh->side()->createSPtr();
m_baseAI = m_baseSide->arrayIndex()->createSPtr();
m_baseAI->setMode( GL_TRIANGLES );
m_indexForSmoothCount = 0;

p_updatePersent();
}


void Loader3DS::User3dFace( unsigned short a, unsigned short b, unsigned short c, unsigned short )
{
m_baseAI->index()->appendVar( a + m_indexOffset );
m_baseAI->index()->appendVar( b + m_indexOffset );
m_baseAI->index()->appendVar( c + m_indexOffset );
}


void Loader3DS::UserFaceSmoothList( uint Index )
{
m_baseSide->appendSmoothFace( Index, m_indexForSmoothCount );
m_indexForSmoothCount++;
}



/**************************************************************
********************* Material on side ***********************
*************************************************************/

void Loader3DS::UserFaceMaterialName( string name )
{
m_baseSideMaterial = m_baseMesh->side()->createSPtr();;
m_baseAIMaterial = m_baseSideMaterial->arrayIndex()->createSPtr();
m_baseAIMaterial->setMode( GL_TRIANGLES );
m_baseSideMaterial->setMaterialId( m_mapMaterial[name] );
}


void Loader3DS::UserFaceMaterialNumber( int number )
{
uint a = m_baseAI->index()->atRo( number * 3 )[0];
uint b = m_baseAI->index()->atRo( number * 3 )[1];
uint c = m_baseAI->index()->atRo( number * 3 )[2];

m_baseAIMaterial->index()->appendVar( a );
m_baseAIMaterial->index()->appendVar( b );
m_baseAIMaterial->index()->appendVar( c );

m_baseAI->index()->atRw( number*3 )[0] = ( uint ) - 1;
m_baseAI->index()->atRw( number*3 )[1] = ( uint ) - 1;
m_baseAI->index()->atRw( number*3 )[2] = ( uint ) - 1;
}


void Loader3DS::User3dFaceFinish()
{
SPtr<BaseSide> oldBaseSide = m_baseSide;
SPtr<BaseAI> oldBaseAI = m_baseAI;

m_baseSide = m_baseMesh->side()->createSPtr();
m_baseAI = m_baseSide->arrayIndex()->createSPtr();
m_baseAI->setMode( GL_TRIANGLES );

for ( uint i = 0, a = 0; i < oldBaseAI->index()->count(); i++ )
{
a = oldBaseAI->index()->atRo( i )[0];
if ( a != ( uint ) - 1 ) m_baseAI->index()->appendVar( a );
}

m_baseMesh->side()->removeBySPtr( oldBaseSide );

if ( !m_baseAI->index()->count() )
m_baseMesh->side()->removeBySPtr( m_baseSide );
}


}

[/CODE]

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  

  • Partner Spotlight

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
  • Popular Now