这个程序应该允许用户选择茶壶的材料,它会动态变化。所以我做了一个菜单。
我使用 setRGB(在实用程序文件中声明)来设置 3 个 GLfloat 数组的颜色。
createMenu 只是创建从 va_list 读取声音的菜单。
setMaterial 根据通过枚举传递的值设置材质:
typedef enum
{
BlackPlastic= 0,
Brass,
Bronze,
Chrome,
Copper,
Gold,
Peweter,
Silver,
PolishedSilver
}MaterialType;
我将省略我测试过的函数的主体,因为它们工作:
int createMenu(void (*callback) (int),int key, const char* const first, ...)
{
// creates a menu, the number of entries depends on the list length,
// the value starts from zero
}
void setRGB( GLfloat* color, GLfloat red, GLfloat green, GLfloat blue)
{
// Sets the color
}
void setMaterial (GLfloat** material, MaterialType type)
{
// Sets the material color (ambient, diffuse, specular).
}
这就是整个程序。我在这里担心的是我做错了什么,所以茶壶没有被绘制,因为 OpenGL 进入了无效状态。
问题是有时我看不到在窗口中绘制的茶壶,我只是得到一个黑色的窗口。令人难以置信的是,有时工作并且我看到了茶壶,并且我能够更改材料颜色。
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "utility.h"
#include <stdlib.h>
GLfloat width=500, height=500;
GLfloat** material;
GLfloat light[3][3]= { {1,1,0}, {1,0.5,0}, {1,0,0} };
void menuCallback (int choice)
{
setMaterial((GLfloat**)material, choice);
glutPostRedisplay();
}
void init()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-width/2, width/2, -height/2, height/2, 1, 1000);
material= malloc(4*sizeof(GLfloat*));
for(GLuint i=0; i<4; i++)
{
material[i]=malloc(3*sizeof(GLfloat));
}
setRGB(material[3], 1, 1, 0);
setMaterial(material, BlackPlastic);
}
void display()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glShadeModel(GL_FLAT);
glMaterialfv(GL_FRONT, GL_AMBIENT, material[0] );
glMaterialfv(GL_FRONT, GL_DIFFUSE, material[1]);
glMaterialfv(GL_FRONT, GL_SPECULAR, material[2]);
glMaterialfv(GL_FRONT, GL_SHININESS, material[3] );
glLightfv(GL_LIGHT0, GL_AMBIENT, light[0]);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light[1]);
glLightfv(GL_LIGHT0, GL_SPECULAR, light[2]);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glutSolidTeapot(100);
glutSwapBuffers();
}
void keyboard(unsigned char key, int x, int y)
{
}
int main(int argc,char * argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowPosition(100, 100);
glutInitWindowSize(width,height);
glutCreateWindow(*argv);
createMenu(menuCallback, GLUT_LEFT_BUTTON, "Black Plastic", "Brass", "Bronze", "Chrome", "Copper", "Gold", "Peweter", "Silver", "Polished Silver", NULL);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
init();
glutMainLoop();
return 0;
}