且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用opengl函数制作3D窗口以在c中绘制3D点?

更新时间:2023-11-09 22:38:22

  • 您可以使用gluPerspective()(或glFrustum())设置透视投影矩阵
  • 然后gluLookAt()将相机"从原点上侦走,这样您就可以看到自己绘制的内容
  • 还有一些基于计时器的动画,因此您可以看到实际的视角
  • 双重缓冲,因为GLUT_SINGLE在现代的复合窗口管理器上有时很奇怪
    • You can use gluPerspective() (or glFrustum()) to set up a perspective projection matrix
    • And gluLookAt() to scoot the "camera" away from the origin so you can see what you draw
    • And a little bit of timer-based animation so you can see the perspective in action
    • Double-buffering because GLUT_SINGLE is sometimes weird on modern composited window managers
    • 一起:

#include <GL/glut.h>

double rnd( double lo, double hi )
{
    return lo + ( hi - lo ) * ( rand() / static_cast<double>( RAND_MAX ) );
}

double angle = 0.0;
void timer( int value )
{
    angle += 1.0;
    glutTimerFunc( 16, timer, 0 );
    glutPostRedisplay();
}

void display()
{
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    gluPerspective( 60.0, w / h, 0.1, 1000.0 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( 100, 100, 100, 0, 0, 0, 0, 0, 1 );

    glRotated( angle, 0, 0, 1 );

    srand( 0 );
    glBegin( GL_LINES );
    for( size_t i = 0; i < 100; i++ )
    {
        glColor3d( rnd( 0.0, 1.0 ), rnd( 0.0, 1.0 ), rnd( 0.0, 1.0 ) );
        glVertex3d( rnd( -50, 50 ), rnd( -50, 50 ), rnd( -50, 50 ) );
        glVertex3d( rnd( -50, 50 ), rnd( -50, 50 ), rnd( -50, 50 ) );
    }
    glEnd();

    glutSwapBuffers();
}

int main( int argc, char *argv[] )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "Special key" );
    glutDisplayFunc( display );
    glutTimerFunc( 0, timer, 0 );
    glutMainLoop();
}