使用c++ opengl根据二维数组绘制高度图
时间: 2024-10-13 20:09:27 浏览: 29
在C++和OpenGL中,根据二维数组绘制高度图通常涉及以下几个步骤[^1]:
1. **设置窗口和上下文**:
```cpp
// 初始化GLFW库
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
// 创建窗口
GLFWwindow* window = glfwCreateWindow(width, height, "Heightmap", nullptr, nullptr);
```
2. **配置OpenGL设置**:
```cpp
glViewport(0, 0, width, height); // 设置视口
glEnable(GL_DEPTH_TEST); // 启用深度测试
glDepthFunc(GL_LEQUAL); // 使用小于等于比较
```
3. **加载并准备数据**:
```cpp
GLuint vertices; // 储存顶点位置
// 从二维数组中读取高度值并转换为顶点坐标
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j) {
float x = j * vertexStride;
float y = height - i * vertexStride; // 以Y轴为高
vertices[i * width + j] = x;
vertices[i * width + j + 1] = y;
vertices[i * width + j + 2] = heights[i][j];
}
```
4. **创建顶点缓冲对象(VBO)**:
```cpp
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
```
5. **设置顶点属性**:
```cpp
glVertexAttribPointer(vertexPositionAttribute, 3, GL_FLOAT, GL_FALSE, stride, (void*)0);
glEnableVertexAttribArray(vertexPositionAttribute);
```
6. **绘制网格**:
```cpp
glBegin(GL_QUADS);
for (int i = 0; i < height - 1; ++i) {
for (int j = 0; j < width - 1; ++j) {
glTexCoord2f(0, 0); glVertex3fv(&vertices[i * width + j]);
glTexCoord2f(1, 0); glVertex3fv(&vertices[(i + 1) * width + j]);
glTexCoord2f(1, 1); glVertex3fv(&vertices[(i + 1) * width + (j + 1)]);
glTexCoord2f(0, 1); glVertex3fv(&vertices[i * width + (j + 1)]);
}
}
glEnd();
```
7. **清理**:
```cpp
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vboID);
```
完成以上步骤后,你应该能看到根据给定二维数组高度值渲染的高度图。
阅读全文