1. 程式人生 > >圖形學實驗 旋轉茶壺 OpenGL實現

圖形學實驗 旋轉茶壺 OpenGL實現

影象學實驗 旋轉茶壺

環境

Windows10

Visual Studio 2017

配置32和64位OpenGL環境。

實驗程式碼

// 實驗三 旋轉茶壺.cpp: 定義控制檯應用程式的入口點。
//

#include"stdafx.h"
#define GLUT_DISABLE_ATEXIT_HACK
#pragma comment(lib, "glut32.lib")  
#include <windows.h>
#include <gl/gl.h>
#include <GL/glut.h>  
#include<iostream>
#include <stdlib.h>  

using namespace std;
GLfloat roate = 0.0;// set rote of roate ying yu bu hao  bu zhuang le 設定旋轉速率
GLfloat rote = 0.0;//shezhi旋轉角度
GLfloat anglex = 0.0;//X 軸旋轉
GLfloat angley = 0.0;//Y 軸旋轉
GLfloat anglez = 0.0;//Z 軸旋轉
GLint WinW = 400;
GLint WinH = 400;
GLfloat oldx;//當左鍵按下時記錄滑鼠座標  
GLfloat oldy;
void init(void)
{
	glClearColor(1.0, 1.0, 1.0, 1.0); //背景黑色  
}
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0, 0.0, 0.0); //畫筆紅色
	glLoadIdentity();  //載入單位矩陣  
	gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
	glRotatef(rote, 0.0f, 1.0f, 0.0f);
	glRotatef(anglex, 1.0, 0.0, 0.0);
	glRotatef(angley, 0.0, 1.0, 0.0);
	glRotatef(anglez, 0.0, 0.0, 1.0);
	glutWireTeapot(2);
	rote += roate;
	//glRotatef(angle, 0.0, 1.0, 0.0);
	//angle += 1.0f;
	glutSwapBuffers();
}
void reshape(int w, int h)
{
	glViewport(0, 0, (GLsizei)w, (GLsizei)h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void mouse(int button, int state, int x, int y)
{
	if (button == GLUT_LEFT_BUTTON)
	{
		if (state == GLUT_DOWN)
		{
			roate = 0;
			rote = 0;
			oldx = x;//當左鍵按下時記錄滑鼠座標  
			oldy = y;
			cout << "left" << endl;
		}

	}
	if (button == GLUT_RIGHT_BUTTON)
	{
		if (state == GLUT_DOWN)
		{
			roate += 1.0f;
			cout << "right" << endl;
		}

	}

}
void motion(int x, int y)
{
	GLint deltax = oldx - x;
	GLint deltay = oldy - y;
	anglex += 360 * (GLfloat)deltax / (GLfloat)WinW;//根據螢幕上滑鼠滑動的距離來設定旋轉的角度  
	angley += 360 * (GLfloat)deltay / (GLfloat)WinH;
	anglez += 360 * (GLfloat)deltay / (GLfloat)WinH;
	oldx = x;//記錄此時的滑鼠座標,更新滑鼠座標  
	oldy = y;//若是沒有這兩句語句,滑動是旋轉會變得不可控  
	glutPostRedisplay();
	glutPostRedisplay();
}



int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(600, 600);
	glutInitWindowPosition(100, 100);
	glutCreateWindow(argv[0]);
	init();
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);
	glutIdleFunc(display);
	glutMainLoop();
	return 0;
}

實驗結果