• OpenGL重绘及拾取小程序


      这是一个很简单的OpenGL小程序,实现了点击屏幕中矩形拖动的功能,但是我觉得对于OpenGL图形重绘和屏幕拾取是个很好的基础学习。自己边学边做了一中午写出来的(环境是codeblocks),还希望高手能给一些指导,谢谢。

     1 #include <windows.h>
    2 #include <GL/glut.h>
    3
    4 static GLint point[2] = {400, 300}; // 矩形中心位置点坐标
    5 static bool changeState = FALSE; // 点击时鼠标位置是否在矩形中
    6
    7 // 绘制函数
    8 void display()
    9 {
    10 glClear(GL_COLOR_BUFFER_BIT);
    11 glColor3f(1.0, 0.0, 1.0);
    12
    13 glBegin(GL_POLYGON);
    14 glVertex2i(point[0]-25, point[1]-25);
    15 glVertex2i(point[0]+25, point[1]-25);
    16 glVertex2i(point[0]+25, point[1]+25);
    17 glVertex2i(point[0]-25, point[1]+25);
    18 glEnd();
    19
    20 glFlush();
    21 }
    22
    23 // 初始化函数
    24 void init()
    25 {
    26 glClearColor(0.0, 0.0, 0.0, 0.0);
    27
    28 glMatrixMode(GL_PROJECTION);
    29 glLoadIdentity();
    30 glOrtho(0, 800, 600, 0, -1.0, 1.0);
    31 }
    32
    33 // 键盘响应函数
    34 void keyboard(unsigned char key, int x, int y)
    35 {
    36 switch (key) {
    37 case 27:
    38 exit(0);
    39 break;
    40
    41 default:
    42 break;
    43 }
    44 }
    45
    46 // 鼠标点击响应函数
    47 void mouse(int button, int state, int x, int y)
    48 {
    49 if( (button==GLUT_LEFT_BUTTON) && (state==GLUT_DOWN) ) {
    50 // 判断鼠标位置是否在矩形中
    51 if( abs(x-point[0])<25 && abs(y-point[1])<25 ) {
    52 changeState = TRUE;
    53 }
    54 }
    55 else if( (button==GLUT_LEFT_BUTTON) && (state==GLUT_UP) ) {
    56 changeState = FALSE;
    57 }
    58 }
    59
    60 // 鼠标移动响应函数
    61 void mouseMove(int x, int y)
    62 {
    63 glClear(GL_COLOR_BUFFER_BIT);
    64
    65 if(changeState == TRUE) {
    66 point[0] = x;
    67 point[1] = y;
    68
    69 glutPostRedisplay(); // 重绘函数
    70 }
    71 }
    72
    73 int main(int argc, char** argv)
    74 {
    75 glutInit(&argc, argv);
    76 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    77 glutInitWindowSize(800, 600);
    78 glutInitWindowPosition(100, 100);
    79 glutCreateWindow("Redisplay");
    80 init();
    81 glutDisplayFunc(display);
    82 glutMouseFunc(mouse);
    83 glutMotionFunc(mouseMove);
    84 glutKeyboardFunc(keyboard);
    85 glutMainLoop();
    86
    87 return 0;
    88 }



  • 相关阅读:
    51nod贪心算法入门-----完美字符串
    HDU6030----矩阵快速幂
    O(n)求1~n的逆元
    (四)添加签到奖励功能
    (三)开始在OJ上添加签到功能
    (二)OJ的主要文件
    (一)在linux上ubuntu搭建hustOJ系统
    CF 148A Insomnia cure
    lower_bound和upper_bound
    C++ string的常用功能
  • 原文地址:https://www.cnblogs.com/yangxi/p/2361801.html
Copyright © 2020-2023  润新知