简体   繁体   English

使用C ++在opengl中创建正方形网格(2D)

[英]creating a grids of squares (2D) in opengl using c++

I want to make a square (2D) by using several smaller squares(like a grid). 我想通过使用几个较小的正方形(如网格)来制作一个正方形(2D)。 I need to do this because I want to texture an image on the main square and divide the picture into several pixels(the said smaller squares). 我需要执行此操作,因为我想在主正方形上对图像进行纹理处理,然后将图片分成几个像素(即较小的正方形)。

Here's the program:- 这是程序:

int h=1,w=1;
int res=25;// res is the number of smaller squares I want
float hratio=h/res;
float wratio=w/res;

void Draw()
{
float x,y;

for(y=-.5;y<=h;y+=h/res)
 {  
   for(x=-.5;x<=w;x+=w/res)
     {  
        glColor3f(1,1,1);
        glBegin(GL_QUADS); 
        glVertex3f(x,y+(h/res),0);
        glVertex3f(x+(w/res),y+(h/res),0);
        glVertex3f(x+(w/res),y,0);
        glVertex3f(x,y,0);
        glEnd();        
    }    
 }  
glFlush();
glutPostRedisplay();
}

void display(void)
{
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
 Draw();   
 glutSwapBuffers();
 glutPostRedisplay();
}


  int main(int iArgc, char** cppArgv)
   {
   glutInit(&iArgc, cppArgv);
   glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);    
glutInitWindowSize(600, 600);
glutInitWindowPosition(200, 200);   
glutCreateWindow("PIXELS");
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);   
glutMainLoop();
return 0;
}

when I run this program, all I get is a black screen. 当我运行该程序时,我得到的只是一个黑屏。

Try this display function: 试试这个显示功能:

void display() { 
    glClear(GL_COLOR_BUFFER_BIT); 
    glMatrixMode(GL_MODELVIEW); 

    //set viewport
    glViewport(0, 0, screen.width, screen.height);

    //set projection matrix using intrinsic camera params
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float aspect = screen.width*1.0/screen.height;
    //gluPerspective is arbitrarily set, you will have to determine these values based
    //on the intrinsic camera parameters
    gluPerspective(60.0f, aspect, 0.1f, 100.0f); 

    //you will have to set modelview matrix using extrinsic camera params
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0); 

    glLoadIdentity();       
    glTranslatef(0.0, 0.0, -5.0);

    Draw(); 

    glutSwapBuffers();  // Swap the front and back frame buffers (double buffering)
    gluPostRedisplay();
}

In your case screen.width is 600 and screen.height is 600. 在您的情况下,screen.width为600,而screen.height为600。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM