Sign in to follow this  
Adam West

OpenGL lib3ds and texture mapping?

Recommended Posts

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
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
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
[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
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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628388
    • Total Posts
      2982403
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now