glBegin(GL_LINES)有效,但glBegin(GL_POINTS)无法正常工作?

时间:2018-04-25 12:05:44

标签: opengl

我有以下代码从Lion.bmp读取数据并显示图像。

#include<GL/gl.h>
#include<GL/glut.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>

unsigned char data[1000000]; // allocate 3 bytes per pixel
int size;
int width;
int height;

void
drawRGB()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    int i,j;
    for(i=0;i<height;i++)
    {
        for(j=0;j<width;j++)
        {
            /* double R=data[3 * (i * width + j)]/255.0; */
            /* double G=data[3 * (i * width + j) + 1]/255.0; */
            /* double B=data[3 * (i * width + j) + 2]/255.0; */
            /* printf("R=%lf G=%lf B=%lf\n",R,G,B); */
            printf("i=%d j=%d\n",i,j);
            glColor3f(1,0,0);
            glBegin(GL_POINTS);
            glVertex2i(i,j);
            glEnd();
            glFlush();
        }
    }
}

void readBMP(char* filename)
{
    printf("inside readBMP\n");
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    width = *(int*)&info[18];
    height = *(int*)&info[22];
    printf("widht = %d height= %d\n",width, height);

    int size = 3 * width * height;
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);

    for(i = 0; i < size; i += 3)
    {
            unsigned char tmp = data[i];
            data[i] = data[i+2];
            data[i+2] = tmp;
    }
    printf("last in readBMP\n");
}


void
init(void)
{
    /*initialize the x-y co-ordinate*/

    /* glClearColor(0,0,0,0); */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, width,0, height);
    /* glClear(GL_COLOR_BUFFER_BIT); */
    glFlush();
}



int
main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    /* glutInitWindowSize(1000, 1000); */
//  glutInitWindowPosition(400, 400);
    readBMP("Lion.bmp"); 
    init();
    printf("after\n");
    glutCreateWindow("RGB");
    glutDisplayFunc(drawRGB);
    /* drawRGB(); */
    glutMainLoop();
}

为了调试我放glBegin(GL_LINES)它有效但如果放glBegin(GL_POINTS)它不起作用。只画了两点。

glBegin(GL_LINES);
glVertex2i(0,0);
glVertex2i(i,j);
glEnd();

以上更换工作。

Lion.bmp

对于行

对于点

编译
gcc bmpRead.c -lglut -lGLU -lGL

1 个答案:

答案 0 :(得分:1)

正交投影(gluOrtho2D)的设置不起作用,因为任何OpenGL引入都需要valide和current OpenGL Context

OpenGL窗口和上下文由glutCreateWindow创建,但这是在调用init()(执行场景初始化,如gluOrtho2D)之后完成的。

init()之后致电glutCreateWindow,以解决您的问题:

readBMP("Lion.bmp"); 

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("RGB");
init(); // <------------------- after "glutCreateWindow"    

glutDisplayFunc(drawRGB);
glutMainLoop();