所以我正在用c ++开发游戏,我正在使用SDL2和OpenGL / GLEW。我试图只是将基本形状绘制到我的窗口,但是,当它应该绘制一个三角形时,它只是创建一个黑色屏幕。这是代码。
游戏循环:
int main(int argc, char** argv) {
Window window("Test", 600, 400);
RenderingEngine e(window);
e.Init();
while (!window.IsCloseRequested()) {
window.SwapBuffers();
e.Render();
}
return 0;
}
窗口类:
Window::Window(const std::string& title, unsigned int width, unsigned int height) :
m_title(title), m_width(width), m_height(height), m_isCloseRequested(false) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
m_glContext = SDL_GL_CreateContext(m_window);
SDL_GL_MakeCurrent(m_window, m_glContext);
SDL_GL_SetSwapInterval(1);
glewExperimental = GL_TRUE;
GLenum res = glewInit();
if (res != GLEW_OK) {
std::cerr << "Error initializting OpenGL." << std::endl;
exit(1);
}
}
void Window::SwapBuffers() {
SDL_GL_SwapWindow(m_window);
}
RenderingEngine Class:
RenderingEngine::RenderingEngine(const Window& window) : m_window(&window) {
}
RenderingEngine::~RenderingEngine() {
if (m_window) delete m_window;
}
void RenderingEngine::Init() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_FRAMEBUFFER_SRGB);
}
void RenderingEngine::Render() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f(-1.0f, -1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glEnd();
}
我无法弄清楚为什么它没有画到屏幕上,所以非常感谢任何帮助。谢谢!
答案 0 :(得分:1)
您正在设置背面剔除,指定您的正面三角形具有顺时针缠绕顺序,并且您想要剔除非正面的所有内容:
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
但您指定的三角形具有逆时针缠绕顺序:
glVertex3f(-1.0f, -1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
您可以通过在一张纸上绘制点来验证,x轴向右,y轴向上。你会看到点的顺序是在原点附近逆时针方向。
基于此,通过背面剔除消除了您的三角形。由于使用逆时针缠绕顺序更常用于OpenGL,我建议通过将glFrontFace()
调用更改为:
glFrontFace(GL_CCW);
或根本不拨打电话,因为这是默认设置。
答案 1 :(得分:0)
你没有加载View / Projection / Model矩阵......我猜这将是一个问题...如果你想用3.2风格制作你也应该使用着色器