OpenGl 环境搭建与介绍

标签: OpenGl opengl 2d graphic tutorial 发布于:2020-04-12 15:53:57 编辑于:2022-11-15 12:18:44 浏览量:32375

OpenGL 二维图形学教程系列

此系列翻译自:OpenGL Tutorial An Introduction on OpenGL with 2D Graphics

  1. OpenGl 环境搭建与介绍
  2. OpenGl 顶点,图元以及颜色
  3. OpenGL 裁剪区域与视口
  4. OpenGl 平移和旋转
  5. OpenGl 动画
  6. OpenGL 使用 GLUT 处理键盘输入
  7. OpenGL 使用 GLUT 处理鼠标输入

1. 搭建 OpenGL 环境

取决于你的编程平台,有以下教程:

1.1 例子 1:设置 OpenGL 与 GLUT(GL01Hello.cpp)

确保你能够运行以下程序:

/*
 * GL01Hello.cpp: Test OpenGL/GLUT C/C++ Setup
 * Tested under Eclipse CDT with MinGW/Cygwin and CodeBlocks with MinGW
 * To compile with -lfreeglut -lglu32 -lopengl32
 */
#include <windows.h>  // for MS Windows
#include <GL/glut.h>  // GLUT, include glu.h and gl.h
 
/* Handler for window-repaint event. Call back when the window first appears and
   whenever the window needs to be re-painted. */
void display() {
   glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
   glClear(GL_COLOR_BUFFER_BIT);         // Clear the color buffer (background)
 
   // Draw a Red 1x1 Square centered at origin
   glBegin(GL_QUADS);              // Each set of 4 vertices form a quad
      glColor3f(1.0f, 0.0f, 0.0f); // Red
      glVertex2f(-0.5f, -0.5f);    // x, y
      glVertex2f( 0.5f, -0.5f);
      glVertex2f( 0.5f,  0.5f);
      glVertex2f(-0.5f,  0.5f);
   glEnd();
 
   glFlush();  // Render now
}
 
/* Main function: GLUT runs as a console application starting at main()  */
int main(int argc, char** argv) {
   glutInit(&argc, argv);                 // Initialize GLUT
   glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
   glutInitWindowSize(320, 320);   // Set the window's initial width & height
   glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
   glutDisplayFunc(display); // Register display callback handler for window re-paint
   glutMainLoop();           // Enter the event-processing loop
   return 0;
}

#include <windows.h>

注意头文件 “windows.h” 仅在 Windows 平台需要。

#include <GL/glut.h>

我们还需要包含 GLUT 头文件,其已经包含了 “glu.h” 和 “gl.h”。

该程序的剩余部分会在相应的教程中解释。

2. 介绍

OpenGL(开放图形库,Open Graphics Library)是一个跨平台的,具备硬件加速的,语言无关的用于构建 3D(包含2D)图形的工业标准 API。现代计算机大多具备专门的带有独立内存的图像处理单元(GPU)用以加速图形渲染。OpenGL 就是这些图像处理硬件的软件接口。

在我们的 OpenGL 程序中使用了以下三组软件库:

  1. OpenGL 核心库(GL):包含数以百计的函数,以 “gl”开头(例如:glColorglVertexglTranslateglRotate)。OpenGL 核心库通过一组几何图元(例如点,线,多边形)来进行建模。
  2. OpenGL 实用程序库(GLU):基于 OpenGL 核心构建,提供一些重要的实用程序(例如:设置摄像机以及投影),以 “glu”开头(例如:gluLookAtgluPerspective)。
  3. OpenGL 实用工具包(GLUT):OpenGL 被设计为独立于操作系统。因此我们需要 GLUT 来与操作系统进行交互(例如:创建窗口,处理键盘和鼠标输入),其提供的函数以 “glut” 开头(例如:glutCreatewindowglutMouseFunc)。GLUT 是平台无关的,其基于平台相关的 OpenGL 扩展构建,例如对于 X Window 是 GLX,对于 Windows 系统是 WGL,对于 Mac OS 则是 AGL,CGL 或者 Cocoa。

未经允许,禁止转载,本文源站链接:https://iamazing.cn/