给我一段完整的c+opengl代码
时间: 2024-11-09 20:26:28 浏览: 14
Ocean-OpenGL:简单的海洋海水模拟| C ++ OpenGL 4.1
在C++中使用OpenGL创建一个简单的窗口并绘制一个红色正方形,你可以参考以下示例代码。这个例子使用GLFW库作为窗口管理器,GLAD库加载OpenGL函数指针。
首先,确保已经安装并链接了GLFW和GLAD库。然后,编写main.cpp:
```cpp
#include <GLFW/glfw3.h>
#include <glad/glad.h>
// 定义着色器
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n"
"void main() {\n"
" gl_Position = vec4(aPos, 0.0, 1.0);\n"
"}\n";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 fragColor;\n"
"void main() {\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0); // 红色\n"
"}\n";
int main() {
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
// 创建窗口
GLFWwindow* window = glfwCreateWindow(640, 480, "Hello OpenGL", nullptr, nullptr);
if (!window) {
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// 加载OpenGL函数指针
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cerr << "Failed to initialize GLAD" << std::endl;
return -1;
}
// 创建并编译着色器
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// 清除颜色缓冲
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window)) {
// 输入处理...
// 更新...
// 渲染
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
float squareVertices[] = { -0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
-0.5f, 0.5f, 0.0f };
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(float), squareVertices);
glEnableVertexAttribArray(0);
glDrawArrays(GL_QUADS, 0, 4);
// 刷新窗口
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理资源
glDeleteVertexShader(vertexShader);
glDeleteFragmentShader(fragmentShader);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
}
```
阅读全文