#include <GL/glut.h>
//------------- プロトタイプ宣言 ------------------//
void display();
void reshape(int w, int h);
void myMouseFunc(int button,int state,int x,int y);
void myMouseMotion(int x,int y);
void DRAW_XYZ();
void DRAW_TRI();
//------------- 各種データ構造 ------------------------//
//マウスの状態
struct MOUSE
{
int Xstart,Ystart;
bool flag;
double weight;
};
MOUSE MouseStatus={0,0,false,0.5};
//回転関係
struct ObjectRotate
{
double xAngle,yAngle;
};
ObjectRotate ObjRot={0,0};
//------------- OpenGLの初期設定 -------------------------//
void GLUT_INIT()
{
glutInitDisplayMode(GLUT_RGBA| GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(640,480);
}
void GLUT_CALL_FUNC()
{
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(myMouseFunc);
glutMotionFunc(myMouseMotion);
}
void MY_INIT()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
}
//----------- メイン関数 -----------------//
int main(int argc, char **argv)
{
glutInit(&argc,argv);
GLUT_INIT();
glutCreateWindow("test");
GLUT_CALL_FUNC();
MY_INIT();
glutMainLoop();
return 0;
}
//------------- ここから各種コールバック -----------------//
void display()
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(3.0, 4.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glRotated(ObjRot.xAngle,1,0,0);
glRotated(ObjRot.yAngle,0,1,0);
DRAW_XYZ();
glPushAttrib(GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glPushMatrix();
glTranslated(1.5,0,0);
DRAW_TRI();
glPopMatrix();
glPopAttrib();
DRAW_TRI();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(30.0, (double)w / (double)h, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
}
void myMouseFunc(int button,int state,int x,int y)
{
if(button == GLUT_LEFT_BUTTON &&state == GLUT_DOWN){
MouseStatus.Xstart = x;
MouseStatus.Ystart = y;
MouseStatus.flag = true;
}
else{
MouseStatus.flag =false;
}
}
void myMouseMotion(int x,int y)
{
if(MouseStatus.flag == false)return;
static int xdir,ydir;
xdir = x - MouseStatus.Xstart;
ydir = y - MouseStatus.Ystart;
ObjRot.xAngle += (double)ydir * MouseStatus.weight;
ObjRot.yAngle += (double)xdir * MouseStatus.weight;
MouseStatus.Xstart = x;
MouseStatus.Ystart = y;
glutPostRedisplay();
}
//------------ ここから各種関数 ---------------//
void DRAW_XYZ()
{
glBegin(GL_LINES);
glColor3d(0,1,0);//x
glVertex2d(-100,0);
glVertex2d(100, 0);
glColor3d(1,0,0);//y
glVertex2d(0,0);
glVertex2d(0,100);
glColor3d(0,0,1);//z
glVertex3d(0,0,-100);
glVertex3d(0,0, 100);
glEnd();
}
void DRAW_TRI()
{
glColor3d(0,0,1);
glBegin(GL_TRIANGLES);
glVertex3d(0,1,0);
glVertex3d(-0.5, 0,0);
glVertex3d(0.5, 0,0);
glEnd();
glColor3d(1,0,0);
glBegin(GL_TRIANGLES);
glVertex3d(0.2,0.7,-0.3);
glVertex3d(-0.3, -0.3,-0.3);
glVertex3d(0.7, -0.3,-0.3);
glEnd();
glColor3d(1,1,1);
}
【メモ】
実行結果で、右側ポリゴン2つがZバッファOFFで描画される(赤いポリゴンが手前に来る)