簡體   English   中英

僅限OpenGL glDrawElements黑屏

[英]OpenGL glDrawElements only Black Screen

我試圖使用glDrawElements函數繪制一個立方體,但是即使是下面的簡單代碼也只能給我黑屏。 如果有幫助,我正在使用XCode 6進行編程。

//
//  main.cpp
//  Copyright (c) 2014 Guilherme Cardoso. All rights reserved.
//

#include <iostream>
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include <vector>
#include <math.h>

const GLfloat width = 500;
const GLfloat height = 500;

GLubyte cubeIndices[24] = {0,3,2,1,2,3,7,6
    ,0,4,7,3,1,2,6,5,4,5,6,7,0,1,5,4};

GLfloat vertices[][3] =
{{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
    {1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0},
    {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};

GLfloat colors[][3] =
{{0.0,0.0,0.0},{1.0,0.0,0.0},
    {1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
    {1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};

void display(){
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColorPointer(3, GL_FLOAT, 0, colors);
    glVertexPointer(3, GL_FLOAT, 0, vertices);

    //glDrawArrays(GL_QUADS, 0, 24);
    glDrawElements(GL_QUADS, 24,GL_UNSIGNED_BYTE, cubeIndices);
    glDisableClientState(GL_VERTEX_ARRAY);
    glutSwapBuffers();
}

void mouse(int button, int state, int x, int y){

}

void keyboard(unsigned char key, int x, int y){
    if(key=='q' || key == 'Q') exit(0);
}

void init(){
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,width ,height, 0);
    glMatrixMode(GL_MODELVIEW);

    glClearColor (1.0, 1.0, 1.0,1.0);
    //glColor3f(0.0,0.0,0.0);
}

void idle(){

}

int main(int argc,  char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(width, height);
    glutCreateWindow("Assignment 3");
    glutPositionWindow(0, 0);


    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutKeyboardFunc(keyboard);
    glutIdleFunc(idle);

    init();
    glutMainLoop();
}

我已經檢查了一些教程,與我所做的沒有太大不同。

您永遠不會清除顏色,尤其是深度緩沖區。 您應該在display()函數的開頭執行此操作。

另外,您的矩陣設置有點怪異。 您為像素設置了一些正交投影,但是嘗試在[-1,1]范圍內繪制一個立方體,因此它在屏幕上將為2像素寬。

實際上,您的代碼正在繪制多維數據集。 仔細看:P

在此處輸入圖片說明

主要問題是您的預測。 初始GL觀看體積是-1到1的多維數據集,但是繪制的多維數據集 -1到1。對gluOrtho2D的調用定義了OpenGL坐標中的投影,該投影與像素相同,但是由於您的立方體是-1比1只有2個像素大,其余都在屏幕外。

而是放下gluOrtho2D ,它將Z尺寸-1設置為1,只允許您設置X / Y ,並創建一個稍大的投影...

glOrtho(-2, 2, -2, 2, -2, 2);

注意:正如@derhass所建議的那樣,調用glClear非常重要,尤其是在啟用深度測試的情況下(不啟用它,上一次繪制調用中的多維數據集將隱藏更新的多維數據集)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM