1.定义模型所需要的结构体和类

// SysModel.h: interface for the SysModel class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_SYSMODEL_H__64D8409F_767A_4FAF_92FD_45BEC3E5DA88__INCLUDED_)
#define AFX_SYSMODEL_H__64D8409F_767A_4FAF_92FD_45BEC3E5DA88__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

//====================================================================
/* 
MS3D STRUCTURES 
*/

// byte-align structures
#ifdef _MSC_VER
# pragma pack( push, packing )
# pragma pack( 1 )
# define PACK_STRUCT
#elif defined( __GNUC__ )
# define PACK_STRUCT __attribute__((packed))
#else
# error you must byte-align these structures with the appropriate compiler directives
#endif
//===============================================================
typedef unsigned char byte;
typedef unsigned short word;

// File header文件头
struct MS3DHeader//结构体名
{
char m_ID[10];
int m_version;
} PACK_STRUCT;//变量名表列

// Vertex information顶点信息
struct MS3DVertex
{
byte m_flags;
float m_vertex[3];
char m_boneID;
byte m_refCount;
} PACK_STRUCT;

// Triangle information三角形信息
struct MS3DTriangle
{
word m_flags;
word m_vertexIndices[3];//保存了三个顶点的索引
float m_vertexNormals[3][3];//保存了三个顶点的法线
float m_s[3], m_t[3];
byte m_smoothingGroup;
byte m_groupIndex;
} PACK_STRUCT;

// Material information材质信息
struct MS3DMaterial
{
    char m_name[32];
    float m_ambient[4];
    float m_diffuse[4];
    float m_specular[4];
    float m_emissive[4];
    float m_shininess; // 0.0f - 128.0f
    float m_transparency; // 0.0f - 1.0f
    byte m_mode; // 0, 1, 2 is unused now
    char m_texture[128];
    char m_alphamap[128];
} PACK_STRUCT;

// Joint information接合信息
struct MS3DJoint//还没有用到
{
byte m_flags;
char m_name[32];
char m_parentName[32];
float m_rotation[3];
float m_translation[3];
word m_numRotationKeyframes;
word m_numTranslationKeyframes;
} PACK_STRUCT;

// Keyframe data起限制作用的数据
struct MS3DKeyframe//还没有用到
{
float m_time;
float m_parameter[3];
} PACK_STRUCT;

// Default alignment
#ifdef _MSC_VER
# pragma pack( pop, packing )
#endif

#undef PACK_STRUCT
//=====================================================================

 

class SysModel 
{

public:
void reloadTextures();
void draw();
bool loadModelData( const char *filename );
SysModel();
virtual ~SysModel();
private: 
// Mesh
typedef struct{
   int m_materialIndex;//材料索引
   int m_numTriangles;//三角形数量
   int *m_pTriangleIndices;//三角索引
}Mesh;



// Material properties//材质
struct Material
{//        环境光        漫反射        镜面光        放射性光
   float m_ambient[4], m_diffuse[4], m_specular[4], m_emissive[4];//光
   float m_shininess;//发光
   GLuint m_texture;//纹理
   char *m_pTextureFilename;//纹理地址名
};

// Triangle structure三角结构
struct Triangle
{
   float m_vertexNormals[3][3];
   float m_s[3], m_t[3];
   int m_vertexIndices[3];
};

// Vertex structure顶点
struct Vertex
{
   char m_boneID; // for skeletal animation活动的骨骼
   float m_location[3];//位置
};
protected:
AUX_RGBImageRec * LoadBMP(const char *Filename);
GLuint LoadGLTexture( const char *filename );
   // Meshes used
   int m_numMeshes;
   Mesh *m_pMeshes;

   // Materials used
   int m_numMaterials;
   Material *m_pMaterials;//材质指针

   // Triangles used
   int m_numTriangles;
   Triangle *m_pTriangles;

   // Vertices Used
   int m_numVertices;
   Vertex *m_pVertices;
  
};

#endif // !defined(AFX_SYSMODEL_H__64D8409F_767A_4FAF_92FD_45BEC3E5DA88__INCLUDED_)

2.类实现方法

// SysModel.cpp: implementation of the SysModel class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SysModel.h"
#include <fstream.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

SysModel::SysModel()
{
   //reloadTextures();
}

SysModel::~SysModel()
{

}

bool SysModel::loadModelData(const char *filename)
{
    //--------------读取文件头 ---------------------
ifstream inputFile( filename, ios::in | ios::binary | ios::nocreate );
if ( inputFile.fail())
   return false; // 无法打开文件

// 以二进制的方式打开文件,如果失败则返回 
inputFile.seekg( 0, ios::end );
long fileSize = inputFile.tellg();
inputFile.seekg( 0, ios::beg );

    //返回文件大小
byte *pBuffer = new byte[fileSize];
inputFile.read( pBuffer, fileSize );
inputFile.close();

    // 分配一个内存,载入文件,并关闭文件
const byte *pPtr = pBuffer;
MS3DHeader *pHeader = ( MS3DHeader* )pPtr;
pPtr += sizeof( MS3DHeader );

if ( strncmp( pHeader->m_ID, "MS3D000000", 10 ) != 0 )
   return false; // 如果不是一个有效的MS3D文件则返回


if ( pHeader->m_version < 3 || pHeader->m_version > 4 )
   return false; // // 如果不能支持这种版本的文件,则返回失败Only Milkshape3D Version 1.3 and 1.4 is supported." );

//----------读取顶点数据 --------------------------------------
int nVertices = *( word* )pPtr; 
m_numVertices = nVertices;
m_pVertices = new Vertex[nVertices];
pPtr += sizeof( word );

int i;
for ( i = 0; i < nVertices; i++ )
{
   MS3DVertex *pVertex = ( MS3DVertex* )pPtr;
   m_pVertices[i].m_boneID = pVertex->m_boneID;
   memcpy( m_pVertices[i].m_location, pVertex->m_vertex, sizeof( float )*3 );
   pPtr += sizeof( MS3DVertex );
}
//---------------------------------------------------------------------
//--------读取三角形信息,因为MS3D使用窗口坐标系而OpenGL使用笛卡儿坐标系,
//--------所以需要反转每个顶点Y方向的纹理坐标

int nTriangles = *( word* )pPtr;
m_numTriangles = nTriangles;
m_pTriangles = new Triangle[nTriangles];
pPtr += sizeof( word );

for ( i = 0; i < nTriangles; i++ )
{
   MS3DTriangle *pTriangle = ( MS3DTriangle* )pPtr;
   int vertexIndices[3] = { pTriangle->m_vertexIndices[0], pTriangle->m_vertexIndices[1], pTriangle->m_vertexIndices[2] };
   float t[3] = { 1.0f-pTriangle->m_t[0], 1.0f-pTriangle->m_t[1], 1.0f-pTriangle->m_t[2] };
   memcpy( m_pTriangles[i].m_vertexNormals, pTriangle->m_vertexNormals, sizeof( float )*3*3 );
   memcpy( m_pTriangles[i].m_s, pTriangle->m_s, sizeof( float )*3 );
   memcpy( m_pTriangles[i].m_t, t, sizeof( float )*3 );
   memcpy( m_pTriangles[i].m_vertexIndices, vertexIndices, sizeof( int )*3 );
   pPtr += sizeof( MS3DTriangle );
}


//-------------------------------------------------------------------------
//-----------------填充网格结构--------------------------------------------
int nGroups = *( word* )pPtr;
m_numMeshes = nGroups;
m_pMeshes = new Mesh[nGroups];
pPtr += sizeof( word );
for ( i = 0; i < nGroups; i++ )
{
   pPtr += sizeof( byte ); // flags
   pPtr += 32;     // name

   word nTriangles = *( word* )pPtr;
   pPtr += sizeof( word );
   int *pTriangleIndices = new int[nTriangles];
   for ( int j = 0; j < nTriangles; j++ )
   {
    pTriangleIndices[j] = *( word* )pPtr;
    pPtr += sizeof( word );
   }

   char materialIndex = *( char* )pPtr;
   pPtr += sizeof( char );

   m_pMeshes[i].m_materialIndex = materialIndex;
   m_pMeshes[i].m_numTriangles = nTriangles;
   m_pMeshes[i].m_pTriangleIndices = pTriangleIndices;
}


//----------------------------------------------
//----------------加载纹理数据------------------
int nMaterials = *( word* )pPtr;
m_numMaterials = nMaterials;
m_pMaterials = new Material[nMaterials];
pPtr += sizeof( word );
for ( i = 0; i < nMaterials; i++ )
{
   MS3DMaterial *pMaterial = ( MS3DMaterial* )pPtr;
   memcpy( m_pMaterials[i].m_ambient, pMaterial->m_ambient, sizeof( float )*4 );
   memcpy( m_pMaterials[i].m_diffuse, pMaterial->m_diffuse, sizeof( float )*4 );
   memcpy( m_pMaterials[i].m_specular, pMaterial->m_specular, sizeof( float )*4 );
   memcpy( m_pMaterials[i].m_emissive, pMaterial->m_emissive, sizeof( float )*4 );
   m_pMaterials[i].m_shininess = pMaterial->m_shininess;
   //纹理地址
   m_pMaterials[i].m_pTextureFilename = new char[strlen( pMaterial->m_texture )+1];

   strcpy( m_pMaterials[i].m_pTextureFilename, pMaterial->m_texture );
   pPtr += sizeof( MS3DMaterial );
}

reloadTextures();///-----------------导入纹理

delete[] pBuffer;

return true;
}

void SysModel::draw()
{
GLboolean texEnabled = glIsEnabled( GL_TEXTURE_2D );

// Draw by group
for ( int i = 0; i < m_numMeshes; i++ )
{
   int materialIndex = m_pMeshes[i].m_materialIndex;
   if ( materialIndex >= 0 )
   {
    glMaterialfv( GL_FRONT, GL_AMBIENT, m_pMaterials[materialIndex].m_ambient );
    glMaterialfv( GL_FRONT, GL_DIFFUSE, m_pMaterials[materialIndex].m_diffuse );
    glMaterialfv( GL_FRONT, GL_SPECULAR, m_pMaterials[materialIndex].m_specular );
    glMaterialfv( GL_FRONT, GL_EMISSION, m_pMaterials[materialIndex].m_emissive );
    glMaterialf( GL_FRONT, GL_SHININESS, m_pMaterials[materialIndex].m_shininess );

    if ( m_pMaterials[materialIndex].m_texture > 0 )
    {
     //绑定模型纹理
     glBindTexture( GL_TEXTURE_2D, m_pMaterials[materialIndex].m_texture );
     glEnable( GL_TEXTURE_2D );
    }
    else
     glDisable( GL_TEXTURE_2D );
   }
   else
   {
    // Material properties?
    glDisable( GL_TEXTURE_2D );
   }

   glBegin( GL_TRIANGLES );//画三角形
   {
    for ( int j = 0; j < m_pMeshes[i].m_numTriangles; j++ )
    {
     int triangleIndex = m_pMeshes[i].m_pTriangleIndices[j];
     const Triangle* pTri = &m_pTriangles[triangleIndex];

     for ( int k = 0; k < 3; k++ )
     {
      int index = pTri->m_vertexIndices[k];

      glNormal3fv( pTri->m_vertexNormals[k] );
      glTexCoord2f( pTri->m_s[k], pTri->m_t[k] );
      glVertex3fv( m_pVertices[index].m_location );
     }
    }
   }
   glEnd();
}

if ( texEnabled )
   glEnable( GL_TEXTURE_2D );
else
   glDisable( GL_TEXTURE_2D );
}

void SysModel::reloadTextures()
{
    for ( int i = 0; i < m_numMaterials; i++ )
        if ( strlen( m_pMaterials[i].m_pTextureFilename ) > 0 )
            m_pMaterials[i].m_texture = LoadGLTexture( m_pMaterials[i].m_pTextureFilename );
        else
            m_pMaterials[i].m_texture = 0;
}

GLuint SysModel::LoadGLTexture(const char *filename)
{
AUX_RGBImageRec *pImage;           // Create Storage Space For The Texture
GLuint texture = 0;             // Texture ID

pImage = LoadBMP( filename );          // Loads The Bitmap Specified By filename

// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if ( pImage != NULL && pImage->data != NULL )      // If Texture Image Exists
{
   glGenTextures(1, &texture);          // Create The Texture

   // Typical Texture Generation Using Data From The Bitmap
   glBindTexture(GL_TEXTURE_2D, texture);
   glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->sizeX, pImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

   free(pImage->data);            // Free The Texture Image Memory
   free(pImage);             // Free The Image Structure
}

return texture;              // Return The Status
}

AUX_RGBImageRec * SysModel::LoadBMP(const char *Filename)
{
FILE *File=NULL;             // File Handle

if (!Filename)              // Make Sure A Filename Was Given
{
   return NULL;             // If Not Return NULL
}

File=fopen(Filename,"r");           // Check To See If The File Exists

if (File)               // Does The File Exist?
{
   fclose(File);             // Close The Handle
   return auxDIBImageLoad(Filename);        // Load The Bitmap And Return A Pointer
}

return NULL;              // If Load Failed Return NULL
}

posted on 2012-12-18 22:44  sgnannan  阅读(757)  评论(1编辑  收藏  举报