我已經寫了一些OpenGL代碼在c + +渲染一個紅色的三角形到屏幕上。該程序使用opengl 3.3和glsl版本330.我已經縮小了不適用於幾個.cpp類文件或我的glsl代碼的代碼。我沒有得到編譯器或鏈接器錯誤(我確實得到了一些鏈接器警告,但我不認爲這些很重要)。我已經給出了我認爲是最可能發生錯誤的地方的代碼。OpenGL三角形不渲染
Renderer.cpp:
#include "Renderer.h"
#include <GL/glew.h>
void Renderer::render(int vbo){
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
ShaderProgram.cpp
#pragma warning(disable:4101)
#include "ShaderProgram.h"
#include <fstream>
#include <sstream>
ShaderProgram::ShaderProgram(std::string vertexLocation, std::string fragmentLocation){
programID = glCreateProgram();
vertexID = glCreateShader(GL_VERTEX_SHADER);
fragmentID = glCreateShader(GL_FRAGMENT_SHADER);
createShader(vertexID, vertexLocation);
createShader(fragmentID, fragmentLocation);
glLinkProgram(programID);
GLint success;
glGetProgramiv(programID, GL_LINK_STATUS, &success);
if (success == 0) {
GLchar ErrorLog[1024];
glGetProgramInfoLog(programID, sizeof(ErrorLog), nullptr, ErrorLog);
fprintf(stderr, "Error linking shader program: '%s'\n", ErrorLog);
}
glValidateProgram(programID);
glUseProgram(programID);
}
void ShaderProgram::createShader(GLint shaderID, std::string srcLocation){
const std::string shaderText = loadShaderSource(srcLocation);
const GLchar* shaderSource = shaderText.data();
glShaderSource(shaderID, 1, &shaderSource, nullptr);
glCompileShader(shaderID);
GLint success;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar InfoLog[1024];
glGetShaderInfoLog(shaderID, sizeof(InfoLog), nullptr, InfoLog);
fprintf(stderr, "Error compiling shader: '%s'\n", InfoLog);
}
glAttachShader(programID, shaderID);
}
std::string ShaderProgram::loadShaderSource(std::string location){
std::ifstream file (location);
std::string source;
std::stringstream stringStream;
if (!file.is_open()){
throw std::runtime_error("Could not open file " + location);
}
stringStream << file.rdbuf();
source = stringStream.str();
return source;
}
Entity.cpp
#include "Entity.h"
Entity::Entity(){
vertices[0] = glm::vec3(-1.0f, -1.0f, 0.0f);
vertices[1] = glm::vec3(1.0f, -1.0f, 0.0f);
vertices[2] = glm::vec3(0.0f, 1.0f, 0.0f);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
}
int Entity::getID(){
return vbo;
}
GLSL代碼:
頂點着色器:
#version 330
layout (location = 0) in vec3 position;
void main(){
gl_Position = vec4(0.5 * position.x, 0.5 * position.y, position.z, 1.0);
}
片段着色器:
#version 330
out vec4 colour;
void main(){
colour = vec4(1.0, 0.0, 0.0, 1.0);
}
您必須使用頂點數組對象(VAO)。 – Ripi2
@ Ripi2:在兼容性上下文中,VAO是可選的。 – genpfault
好的,謝謝。當我有空時,我會在明天嘗試。我跟隨的教程並不是我猜測的最好的。他們沒有得到我很好的結果 – Matty2532