本人在学习opengl做项目时,需要设计三维人脸模型。于是寻找多种方案。求得用opengl读取OBJ模型文件,并进行纹理修饰这一解决方案。在使用中用到了glm库。以下是我对glm.c库的两篇分析。http://blog.csdn.net/a350203223/article/details/10093135
http://blog.csdn.net/a350203223/article/details/10045665
以下是进行解决读取OBJ文件并进行纹理修饰的主要程序。希望能给大家有所帮助,如果分析中有不恰当的地方,望批评指正。建议花点时间自己研究,全部程序不会给出。运行结果如下:
void RenderScene(void)
{
static GLfloat dark[4] = { 0.0, 0.0, 0.0, 1.0 };
static GLfloat normal[4] = { 0.5, 0.5, 0.5, 1.0 };
static GLfloat bright[4] = { 1.0, 1.0, 1.0, 1.0 };
static GLfloat pos[4] = { -0.2588, 0.0, 0.9659, 0.0 };
/* Clear the window */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Setup for drawing... */
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
if (!pmodel) {
pmodel = glmReadOBJ("obj/刘德华.obj");//读取OBJ文件
if (!pmodel) exit(0);
glmUnitize(pmodel);//单位化模型model并返回缩放比例因子,单位化就是把模型通过平移和缩放变换限制到3维坐标系中点为中心的一个单位正方体区域内
glmFacetNormals(pmodel);//计算模型面的法向(假定多边形顶点顺序为逆时针)
glmVertexNormals(pmodel, 90.0);//计算模型的平滑顶点法向,angle参数为平滑交叉的最大角度(角度制)
}
TexBits = LoadDIBitmap("obj/刘德华.bmp", &TexInfo);
glPushMatrix();
glTranslatef(0, 0, -3);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, dark);
glLightfv(GL_LIGHT0, GL_DIFFUSE, dark);
glLightfv(GL_LIGHT0, GL_SPECULAR, bright);
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glMaterialfv(GL_FRONT, GL_AMBIENT, dark);
glMaterialfv(GL_FRONT, GL_DIFFUSE, dark);
glMaterialfv(GL_FRONT, GL_SPECULAR, bright);
glMateriali(GL_FRONT, GL_SHININESS, 128);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TexInfo->bmiHeader.biWidth,
TexInfo->bmiHeader.biHeight, 0, GL_BGR_EXT,
GL_UNSIGNED_BYTE, TexBits);
glmDraw(pmodel,GLM_SMOOTH |GLM_TEXTURE | GLM_MATERIAL);//先画一个实体——无纹理
glBlendFunc(GL_ONE, GL_ONE);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, normal);
glLightfv(GL_LIGHT0, GL_AMBIENT, normal);
glLightfv(GL_LIGHT0, GL_DIFFUSE, normal);
glLightfv(GL_LIGHT0, GL_SPECULAR, dark);
glMaterialfv(GL_FRONT, GL_AMBIENT, normal);
glMaterialfv(GL_FRONT, GL_DIFFUSE, normal);
glMaterialfv(GL_FRONT, GL_SPECULAR, dark);
glMateriali(GL_FRONT, GL_SHININESS, 0);
glmDraw(pmodel,GLM_SMOOTH |GLM_TEXTURE | GLM_MATERIAL);//再画一个经纹理修饰和光照处理后的人物
glPopMatrix();
glutSwapBuffers();
}