所以我前几天尝试了一些opengl代码。这是我的代码。 主:
#include <glew.h>
#include <glfw3.h>
#include "Mesh.h"
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
int main(int argc, char** argv){
glfwInit();
GLFWwindow* window = glfwCreateWindow(1024, 768, "HGLW", NULL, NULL);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
int succes = glewInit();
if (succes != GLEW_OK){
exit(EXIT_FAILURE);
glfwTerminate();
}
glEnable(GL_DEPTH);
glDepthFunc(GL_LESS);
Mesh mesh();
mesh.setShader(GL_VERTEX_SHADER, "Shaders/Shader.vert");
mesh.setShader(GL_FRAGMENT_SHADER, "Shaders/Shader.frag");
mesh.linkShaders();
mesh.upload();
while (!glfwWindowShouldClose(window)){
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mesh.render();
glfwSwapBuffers(window);
}
return 0;
}
相关网格功能:
Mesh::Mesh(){
//generate the vertex and index buffers
glGenBuffers(1, &_vbo);
glGenBuffers(1, &_ibo);
//generating the vertex array
glGenVertexArrays(1, &_vao);
//link the right buffers to the vao
glBindVertexArray(_vao);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo);
glBindVertexArray(0);
}
void Mesh::upload()
{
std::vector<GLfloat> verts = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f };
_indices = { 0, 1, 2};
glBindVertexArray(_vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)(sizeof(GLfloat)*3));
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*verts.size(), &verts[0], GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort)*_indices.size(), &_indices[0], GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Mesh::render(){
//if the program exists, use it
if (_program != NULL){
glUseProgram(_program);
}
glBindVertexArray(_vao);
glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_SHORT, 0);
glBindVertexArray(NULL);
}
顶点着色器:
#version 430
layout(location=0) in vec3 position;
layout(location=1) in vec3 inColor;
out vec3 outColor;
void main(){
gl_Position = vec4(position, 0.0f);
outColor = inColor;
}
片段着色器:
#version 430
in vec3 outColor;
out vec4 color;
void main(){
color = vec4(outColor, 1.0f);
}
我得到的不是红色,绿色和蓝色三角形,而是完全红色的三角形。当我将第一种颜色(顶点的第四,第五和第六个元素)更改为绿色时,我的整个三角形变为绿色。所以看起来我的整个三角形都有第一个指定的颜色,而不是全部三个。
有谁知道这里发生了什么?我以前做过这些类型的程序,它们都运行良好;我无法找到我的工作程序和这个程序之间的任何真正差异。
我使用的是opengl 4.5