几个opengl立方体绘制案例

VC6 下载
http://blog.csdn.net/bcbobo21cn/article/details/44200205


opengl环境配置
http://blog.csdn.net/bcbobo21cn/article/details/51044614#t4


下面的demoproject
http://pan.baidu.com/s/1mhT1FIw

一  OpenGL 绘制一个立方体

代码

#include<GL/glut.h>

// 绘制立方体


// 将立方体的八个顶点保存到一个数组里面 

static const float vertex_list[][3] = 
{ 
    -0.5f, -0.5f, -0.5f, 
    0.5f, -0.5f, -0.5f, 
    -0.5f, 0.5f, -0.5f, 
    0.5f, 0.5f, -0.5f, 
    -0.5f, -0.5f, 0.5f, 
    0.5f, -0.5f, 0.5f, 
    -0.5f, 0.5f, 0.5f, 
    0.5f, 0.5f, 0.5f, 
}; 

// 将要使用的顶点的序号保存到一个数组里面 

static const GLint index_list[][2] = 
{ 
    {0, 1},    
    {2, 3},    
    {4, 5},    
    {6, 7},    
    {0, 2},    
    {1, 3},    
    {4, 6},    
    {5, 7},
    {0, 4},
    {1, 5},
    {7, 3},
    {2, 6}
}; 

// 绘制立方体

void DrawCube(void)
{
    int i,j;
    
    glBegin(GL_LINES); 
    for(i=0; i<12; ++i) // 12 条线段

    {
        for(j=0; j<2; ++j) // 每条线段 2个顶点

        {
            glVertex3fv(vertex_list[index_list[i][j]]);     
        }
    }
    glEnd();
}

static float rotate = 0;
static int times = 0;

void renderScene(void) 
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity();
    glPushMatrix();

    //glTranslatef(-0.2, 0, 0); // 平移

    //glScalef(2, 1, 1);    // 缩放


    times++;
    if(times > 100)
    {
        times = 0;
    }

    if(times % 100 == 0)
    {
        rotate += 0.3;
    }
    
    glRotatef(rotate, 0, 1, 0);
    glRotatef(rotate, 1, 0, 0);

    glColor3f(0, 0, 1);

    DrawCube();

    glPopMatrix();
    glutSwapBuffers();
}

void main(int argc, char **argv) 
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(500, 500);
    glutCreateWindow("GLDemo");
    glutDisplayFunc(renderScene);
    glutIdleFunc(renderScene);
    glutMainLoop();
}

效果。随时间而动;

glVertex函数用在glBegin和glEnd之间,除此以外没有意义。

用来指定点、线和多边形的顶点。当调用glVertex时。能够为该顶点指定颜色、法线量和纹理坐标。当仅仅指定x。y时。z缺省为0.0,w缺省为1.0;当仅仅指定x、y和z时。w缺省为1.0。


二 3D旋转立方体

代码

/** 
 * function:动态3D立方体 
 */  
#include <windows.h>  
#include <gl/gl.h>  
#include <gl/glu.h>  
  
char *className = "OpenGL";  
char *windowName = "OpenGL Cube";  
int winX = 0, winY = 0;  
int winWidth = 300, winHeight = 300;  
HDC hDC;  
HGLRC hGLRC;  
HPALETTE hPalette;  
void init(void){  
    //设置视图投影  
    glMatrixMode(GL_PROJECTION);  
    glFrustum(-0.5F,0.5F,-0.5F,0.5F,1.0F,3.0F);  
    //视区定位  
    glMatrixMode(GL_MODELVIEW);  
    glTranslatef(0.0F,0.0F,-2.0F);  
    //物体定位  
    glRotatef(30.0F,1.0F,0.0F,0.0F);  
    glRotatef(30.0F,0.0F,1.0F,0.0F);  
    glEnable(GL_DEPTH_TEST);  
    glEnable(GL_LIGHTING);  
    glEnable(GL_LIGHT0);  
}  
void redraw(HDC hDC){  
    //清除颜色和深度缓冲区  
    //glClearColor(1.0f, 0.0f, 0.0f, 0.0f);  
    //glClearDepth(2.0);  
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);  
    //画立方体的6个面  
    glBegin(GL_QUADS);  
    glNormal3f( 0.0F, 0.0F, 1.0F);  
    glVertex3f( 0.5f, 0.5f, 0.5f);  
    glVertex3f(-0.5f, 0.5f, 0.5f);  
    glVertex3f(-0.5f,-0.5f, 0.5f);  
    glVertex3f( 0.5f,-0.5f, 0.5f);  
    //1----------------------------  
    glNormal3f( 0.0F, 0.0F,-1.0F);  
    glVertex3f(-0.1f,-0.5f,-0.5f);  
    glVertex3f(-0.5f, 0.5f,-0.5f);  
    glVertex3f( 0.5f, 0.5f,-0.5f);  
    glVertex3f( 0.5f,-0.5f,-0.5f);  
    //2----------------------------  
    glNormal3f( 0.0F, 1.0F, 0.0F);  
    glVertex3f( 0.5f, 0.5f, 0.5f);  
    glVertex3f( 0.5f, 0.5f,-0.5f);  
    glVertex3f(-0.5f, 0.5f,-0.5f);  
    glVertex3f(-0.5f, 0.5f, 0.5f);  
    //3----------------------------  
    glNormal3f( 0.0F,-1.0F, 0.0F);  
    glVertex3f(-0.5f,-0.5f,-0.5f);  
    glVertex3f( 0.5f,-0.5f,-0.5f);  
    glVertex3f( 0.5f,-0.5f, 0.5f);  
    glVertex3f(-0.5f,-0.5f, 0.5f);  
    //4----------------------------  
    glNormal3f( 1.0F, 0.0F, 0.0F);  
    glVertex3f( 0.5f, 0.5f, 0.5f);  
    glVertex3f( 0.5f,-0.5f, 0.5f);  
    glVertex3f( 0.5f,-0.5f,-0.5f);  
    glVertex3f( 0.5f, 0.5f,-0.5f);  
    //5----------------------------  
    glNormal3f(-1.0F, 0.0F, 0.0F);  
    glVertex3f(-0.5f,-0.5f,-0.5f);  
    glVertex3f(-0.5f,-0.5f, 0.5f);  
    glVertex3f(-0.5f, 0.5f, 0.5f);  
    glVertex3f(-0.5f, 0.5f,-0.5f);  
    //6----------------------------*/  
    glEnd();  
    SwapBuffers(hDC);  
}  
void resize(void){  
    //设置视区。使之覆盖整个窗体  
    glViewport(0,0,winWidth,winHeight);  
}  
void setupPixelFormat(HWND hwnd, HDC* hDC, HGLRC* hRC){  
    PIXELFORMATDESCRIPTOR pfd;  
  
    int iFormat;  
  
    /* get the device context (DC) */  
    *hDC = GetDC(hwnd);  
  
    /* set the pixel format for the DC */  
    ZeroMemory(&pfd, sizeof(pfd));  
  
    pfd.nSize = sizeof(pfd);//结构的大小  
    pfd.nVersion = 1;//版本号  
    pfd.dwFlags = PFD_DRAW_TO_WINDOW |  
                  PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;//支持双缓存  
    pfd.iPixelType = PFD_TYPE_RGBA;//颜色模式  
    pfd.cColorBits = 24;  
    pfd.cDepthBits = 16;//颜色深度  
    pfd.iLayerType = PFD_MAIN_PLANE;//主层  
  
    iFormat = ChoosePixelFormat(*hDC, &pfd);//确定pfd结构是否存在  
  
    SetPixelFormat(*hDC, iFormat, &pfd);  
  
    /* create and enable the render context (RC) */  
    *hRC = wglCreateContext(*hDC);  
  
    wglMakeCurrent(*hDC, *hRC);  
  
  
    /*if(iFormat == 0){ 
        MessageBox(WindowFromDC(hDC),"ChoosePixelFormat failed.", 
                   "Error",MB_ICONERROR|MB_OK); 
        exit(1); 
    } 
    if(SetPixelFormat(hDC,iFormat,&pfd)!=TRUE){ 
        MessageBox(WindowFromDC(hDC),"SetPixelFormat failed.", 
                   "Error",MB_ICONERROR|MB_OK); 
        exit(1); 
    }*/  
}  
void setupPalette(HDC hDC){  
    int pixelFormat = GetPixelFormat(hDC);  
    PIXELFORMATDESCRIPTOR pfd;  
    LOGPALETTE* pPal;  
    int paletteSize;  
    DescribePixelFormat(hDC,pixelFormat,  
                        sizeof(PIXELFORMATDESCRIPTOR),&pfd);  
    if(pfd.dwFlags & PFD_NEED_PALETTE){  
        paletteSize = 1 << pfd.cColorBits;  
    }  
    else{  
        return ;  
    }  
    pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE)+paletteSize*sizeof(PALETTEENTRY));  
    pPal->palVersion=0x300;  
    pPal->palNumEntries = paletteSize;  
    //建一个简单的RGB调色板  
    {  
        int redMask = (1 << pfd.cRedBits) - 1;  
        int greemMask = (1 << pfd.cGreenBits) - 1;  
        int blueMask = (1 << pfd.cBlueBits) - 1;  
        int i;  
        for(i=0;i<paletteSize;i++){  
            pPal->palPalEntry[i].peRed =  
            (((i >> pfd.cRedShift) & redMask) * 255)/greemMask;  
            //pPal->palPalEntry[i]-peGreen =  
  
        }  
    }  
  
}  
  
  
  
  
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);  
void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);  
void DisableOpenGL(HWND, HDC, HGLRC);  
  
  
int WINAPI WinMain(HINSTANCE hInstance,  
                   HINSTANCE hPrevInstance,  
                   LPSTR lpCmdLine,  
                   int nCmdShow)  
{  
    WNDCLASSEX wcex;  
    HWND hwnd;  
    HDC hDC;  
    HGLRC hRC;  
    MSG msg;  
    BOOL bQuit = FALSE;  
    float theta = 0.0f;  
  
    /* register window class */  
    wcex.cbSize = sizeof(WNDCLASSEX);  
    wcex.style = CS_HREDRAW|CS_VREDRAW;//CS_OWNDC;  
    wcex.lpfnWndProc = WindowProc;  
    wcex.cbClsExtra = 0;  
    wcex.cbWndExtra = 0;  
    wcex.hInstance = hInstance;  
    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);  
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);  
    wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);  
    wcex.lpszMenuName = NULL;  
    wcex.lpszClassName = "GLSample";  
    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);;  
  
  
    if (!RegisterClassEx(&wcex))  
        return 0;  
  
    /* create main window */  
    hwnd = CreateWindowEx(0,  
                          "GLSample",  
                          windowName,//"OpenGL Sample",  
                          WS_OVERLAPPEDWINDOW/*后面是后来加的*/|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,  
                          winX,//CW_USEDEFAULT,  
                          winY,//CW_USEDEFAULT,  
                          winWidth,//256,  
                          winHeight,//256,  
                          NULL,  
                          NULL,  
                          hInstance,  
                          NULL);  
  
    ShowWindow(hwnd, nCmdShow);  
  
    /* enable OpenGL for the window */  
    //setupPixelFormat(hwnd, &hDC, &hRC);  
    EnableOpenGL(hwnd, &hDC, &hRC);  
    init();  
  
    /* program main loop */  
    while (!bQuit)  
    {  
        /* check for messages */  
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))  
        {  
            /* handle or dispatch messages */  
            if (msg.message == WM_QUIT)  
            {  
                bQuit = TRUE;  
            }  
            else  
            {  
                TranslateMessage(&msg);  
                DispatchMessage(&msg);  
            }  
        }  
        else if(0)  
        {  
            /* OpenGL animation code goes here */  
  
            glClearColor(0.5f, 1.0f, 0.5f, 0.5f);  
            glClear(GL_COLOR_BUFFER_BIT);  
  
  
            glPushMatrix();  
            glRotatef(theta, 0.0f, 0.0f, 1.0f);  
  
            glBegin(GL_TRIANGLES);  
  
                glColor3f(0.5f, 5.0f, 1.0f);   glVertex2f(0.0f,   1.0f);  
                glColor3f(0.0f, 1.0f, 0.0f);   glVertex2f(0.87f,  -0.5f);  
                glColor3f(1.0f, 5.0f, 0.5f);   glVertex2f(-0.87f, -0.5f);  
  
            glEnd();  
  
            glPopMatrix();  
  
            SwapBuffers(hDC);  
  
            theta += 1.0f;  
            //Sleep (1);  
        }  
        else{  
            glPushMatrix();  
            glRotatef(theta, 0.0f, 0.0f, 1.0f);  
            redraw(hDC);//立方体  须要初始化init()函数  
            glPopMatrix();  
            theta += 1.0f;  
        }  
    }  
  
    /* shutdown OpenGL */  
    DisableOpenGL(hwnd, hDC, hRC);  
  
    /* destroy the window explicitly */  
    DestroyWindow(hwnd);  
  
    return msg.wParam;  
}  
  
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)  
{  
    switch (uMsg)  
    {  
        /*case WM_CREATE: 
            hDC = GetDC(hwnd); 
            setupPalette(hDC); 
            hGLRC=wglCreateContext(hDC); 
            wglMakeCurrent(hDC,hGLRC); 
            init(); 
            return 0;*/  
        case WM_CLOSE:  
            PostQuitMessage(0);  
        break;  
  
        case WM_DESTROY:  
            /*//------------------ 
            if(hGLRC){ 
                wglMakeCurrent(NULL,NULL); 
                wglDeleteContext(hGLRC); 
            } 
            if(hPalette){ 
                DeleteObject(hPalette); 
            } 
            ReleaseDC(hwnd,hDC); 
            PostQuitMessage(0); 
            //====================*/  
            return 0;  
        //------------------------  
        case WM_SIZE:  
            //跟踪窗体大小改变  
            hGLRC=(struct HGLRC__ *)1;  
            if(hGLRC){  
                winWidth=(int)LOWORD(lParam);  
                winHeight=(int)LOWORD(lParam);  
                resize();  
                return 0;  
            }  
        case WM_PALETTECHANGED:  
            //假设它不是当前窗体,则实现调色板与hDC的相应  
            if(hGLRC && hPalette && (HWND) wParam != hwnd){  
                UnrealizeObject(hPalette);  
                SelectPalette(hDC,hPalette,FALSE);  
                //ReadlizePalette(hDC);  
                redraw(hDC);  
                break;  
            }  
        break;  
        //=========================  
        case WM_KEYDOWN:  
        {  
            switch (wParam)  
            {  
                case VK_ESCAPE:  
                    PostQuitMessage(0);  
                break;  
            }  
        }  
        break;  
  
        default:  
            return DefWindowProc(hwnd, uMsg, wParam, lParam);  
    }  
  
    return 0;  
}  
  
void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)  
{  
    PIXELFORMATDESCRIPTOR pfd;  
  
    int iFormat;  
  
    /* get the device context (DC) */  
    *hDC = GetDC(hwnd);  
  
    /* set the pixel format for the DC */  
    ZeroMemory(&pfd, sizeof(pfd));  
  
    pfd.nSize = sizeof(pfd);  
    pfd.nVersion = 1;  
    pfd.dwFlags = PFD_DRAW_TO_WINDOW |  
                  PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;  
    pfd.iPixelType = PFD_TYPE_RGBA;  
    pfd.cColorBits = 24;  
    pfd.cDepthBits = 16;  
    pfd.iLayerType = PFD_MAIN_PLANE;  
  
    iFormat = ChoosePixelFormat(*hDC, &pfd);  
  
    SetPixelFormat(*hDC, iFormat, &pfd);  
  
    /* create and enable the render context (RC) */  
    *hRC = wglCreateContext(*hDC);  
  
    wglMakeCurrent(*hDC, *hRC);  
}  
  
void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)  
{  
    wglMakeCurrent(NULL, NULL);  
    wglDeleteContext(hRC);  
    ReleaseDC(hwnd, hDC);  
} 

建立一个Win32project,如图;样例一是控制台project。


效果;



遇到例如以下错误。

lftdemo2.cpp
e:\dddd13\opengl立方体demo\lftdemo2\lftdemo2.cpp(308) : error C2440: '=' : cannot convert from 'const int' to 'struct HGLRC__ *'
        Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
运行 cl.exe 时出错.


hGLRC=1;

改为
hGLRC=(struct HGLRC__ *)1;


GL_QUADS:绘制由四个顶点组成的一组单独的四边形。顶点4n-3、4n-2、4n-1和4n定义了第n个四边形。总共绘制N/4个四边形


三 3D颜色立方体

代码:

#include <stdio.h>  
#define GLUT_DISABLE_ATEXIT_HACK  
#include <gl/glut.h>  
//#pragma comment(lib, "glut32.lib")  
  
GLfloat AngleX;  
GLfloat AngleY;  
  
void display(void)  
{  
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
  
    glMatrixMode(GL_MODELVIEW);  
    glLoadIdentity();  
  
    glPushMatrix();  
    {  
        glRotatef(AngleX,1.0f,0.0f,0.0f);  
        glRotatef(AngleY,0.0f,1.0f,0.0f);  
  
        glBegin(GL_POLYGON); //前表面  
        glColor3ub((GLubyte)255,(GLubyte)255,(GLubyte)255);//颜色设置为白色  
        glVertex3f(50.0f,50.0f,50.0f);  
  
        glColor3ub((GLubyte)255,(GLubyte)255,(GLubyte)0);//颜色设置为黄色  
        glVertex3f(50.0f,-50.0f,50.0f);  
  
        glColor3ub((GLubyte)255,(GLubyte)0,(GLubyte)0);//颜色设置为红色  
        glVertex3f(-50.0f,-50.0f,50.0f);  
  
        glColor3ub((GLubyte)255,(GLubyte)0,(GLubyte)255);//颜色设置为白色  
        glVertex3f(-50.0f,50.0f,50.0f);  
        glEnd();  
  
        glBegin(GL_POLYGON); //后表面  
        glColor3f(0.0f,1.0f,1.0f);//颜色设置为青色  
        glVertex3f(50.0f,50.0f,-50.0f);  
  
        glColor3f(0.0f,1.0f,0.0f);//颜色设置为绿色  
        glVertex3f(50.0f,-50.0f,-50.0f);  
  
        glColor3f(0.0f,0.0f,0.0f);//颜色设置为黑色  
        glVertex3f(-50.0f,-50.0f,-50.0f);  
  
        glColor3f(0.0f,0.0f,1.0f);//颜色设置为蓝色  
        glVertex3f(-50.0f,50.0f,-50.0f);  
        glEnd();  
  
        glBegin(GL_POLYGON); //上表面  
        glColor3d(0.0,1.0,1.0);//颜色设置为青色  
        glVertex3f(50.0f,50.0f,-50.0f);  
  
        glColor3d(1.0,1.0,1.0);//颜色设置为白色  
        glVertex3f(50.0f,50.0f,50.0f);  
  
        glColor3d(1.0,0.0,1.0);//颜色设置为品红色  
        glVertex3f(-50.0f,50.0f,50.0f);  
  
        glColor3d(0.0,0.0,1.0);//颜色设置为蓝色  
        glVertex3f(-50.0f,50.0f,-50.0f);  
        glEnd();  
  
        glBegin(GL_POLYGON); //下表面  
        glColor3ub(0u,255u,0u);//颜色设置为绿色  
        glVertex3f(50.0f,-50.0f,-50.0f);  
  
        glColor3ub(255u,255u,0u);//颜色设置为黄色  
        glVertex3f(50.0f,-50.0f,50.0f);  
  
        glColor3ub(255u,0u,0u);//颜色设置为红色  
        glVertex3f(-50.0f,-50.0f,50.0f);  
  
        glColor3ub(0u,0u,0u);//颜色设置为黑色  
        glVertex3f(-50.0f,-50.0f,-50.0f);  
        glEnd();  
  
        glBegin(GL_POLYGON); //左表面  
        glColor3ub((GLubyte)255,(GLubyte)255,(GLubyte)255);//颜色设置为白色  
        glVertex3f(50.0f,50.0f,50.0f);  
  
        glColor3ub((GLubyte)0,(GLubyte)255,(GLubyte)255);//颜色设置为青色  
        glVertex3f(50.0f,50.0f,-50.0f);  
  
        glColor3ub((GLubyte)0,(GLubyte)255,(GLubyte)0);//颜色设置为绿色  
        glVertex3f(50.0f,-50.0f,-50.0f);  
  
        glColor3ub((GLubyte)255,(GLubyte)255,(GLubyte)0);//颜色设置为黄色  
        glVertex3f(50.0f,-50.0f,50.0f);  
        glEnd();  
  
        glBegin(GL_POLYGON); //右表面  
        glColor3f(1.0f,0.0f,1.0f);//颜色设置为品红色  
        glVertex3f(-50.0f,50.0f,50.0f);  
  
        glColor3f(0.0f,0.0f,1.0f);//颜色设置为蓝色  
        glVertex3f(-50.0f,50.0f,-50.0f);  
  
        glColor3f(0.0f,0.0f,0.0f);//颜色设置为黑色  
        glVertex3f(-50.0f,-50.0f,-50.0f);  
  
        glColor3f(1.0f,0.0f,0.0f);//颜色设置为红色  
        glVertex3f(-50.0f,-50.0f,50.0f);  
        glEnd();  
    }  
    glPopMatrix();  
  
  
    glutSwapBuffers();  
}  
  
void reshape(int w, int h)  
{  
    GLfloat aspect = (GLfloat)w / (GLfloat)h;  
    GLfloat nRange = 100.0f;  
  
    glViewport(0,0,w,h);  
  
    glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影模式  
    glLoadIdentity();  
  
    //设置三维投影区  
  
    if (w<=h)  
    {  
        glOrtho(-nRange, nRange, -nRange * aspect, nRange * aspect, -nRange, nRange);  
    }   
    else  
    {  
        glOrtho(-nRange, nRange, -nRange / aspect, nRange / aspect, -nRange, nRange);  
    }  
}  
  
void key_board(GLint key,GLint x,GLint y)  
{  
    if(key == GLUT_KEY_UP)  
    {  
        AngleX -= 5.0f;  
    }  
    if(key == GLUT_KEY_DOWN)  
    {  
        AngleX += 5.0f;  
    }  
    if(key == GLUT_KEY_LEFT)  
    {  
        AngleY -= 5.0f;  
    }  
    if(key == GLUT_KEY_RIGHT)  
    {  
        AngleY += 5.0f;  
    }  
    if(AngleX > 355.0f)  
    {  
        AngleX = 0.0f;  
    }  
    if(AngleX < 0.0f)  
    {  
        AngleX = 355.0f;  
    }  
    if(AngleY > 355.0f)  
        AngleY = 0.0f;  
  
    if(AngleY < 0.0f)  
    {  
        AngleY = 355.0f;  
    }  
    glutPostRedisplay();  
}  
  
void init()  
{  
    AngleX = 45.0f;  
    AngleY = 315.0f;  
  
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);  
  
    glEnable(GL_DEPTH_TEST);  
    glEnable(GL_DITHER);  
    glShadeModel(GL_SMOOTH);  
}  
void main(int argc,char* argv[])  
{  
    glutInit(&argc,argv);  
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);  
    glutInitWindowSize(480,480);  
    glutCreateWindow("OpenGL颜色立方体");  
  
    glutReshapeFunc(reshape);  
    glutDisplayFunc(display);  
    glutSpecialFunc(key_board); //设置处理特殊击键的回调函数  
  
    init();  
  
    glutMainLoop();  
}

效果:



四 光照立方体效果

代码:

#include <windows.h>  
#include <gl/gl.h>  
#include <gl/glu.h>  

#define WIN32_LEAN_AND_MEAN

//#pragma comment(lib, "openGL32.lib")
//#pragma comment(lib, "glu32.lib")
//#pragma comment(lib, "glaux.lib")
float angle=0.0f;
HDC g_HDC;
float legAngle[2]={0.0f,0.0f};
float armAngle[2]={0.0f,0.0f};
float ambientLight[]={0.1f,0.3f,0.8f,1.0f};  //环境光
float diffuseLight[]={0.25f,0.25f,0.25f,1.0f}; //散射光
float lightPosition[]={0.0f,0.0f,1.0f,0.0f}; //光源位置
//材质变量
float matAmbient[]={1.0f,1.0f,1.0f,1.0f};
float matDiff[]={1.0f,1.0f,1.0f,1.0f};
//初始化
void Initialize()
{
 glClearColor(0.0f,0.0f,0.0f,0.0f);   //清理颜色为黑色
 glShadeModel(GL_SMOOTH);     //使用平滑明暗处理
 glEnable(GL_DEPTH_TEST);     //剔除隐藏面
 glEnable(GL_CULL_FACE);      //不计算多边形背面
 glFrontFace(GL_CCW);      //多边形逆时针方向为正面
 glEnable(GL_LIGHTING);      //启用光照
 //为LIGHT0设置析质
 glMaterialfv(GL_FRONT,GL_AMBIENT,matAmbient);
 glMaterialfv(GL_FRONT,GL_DIFFUSE,matDiff);
 //如今開始调协LIGHT0
 glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight); //设置环境光分量
 glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight); //设置散射光分量
 glLightfv(GL_LIGHT0,GL_POSITION,lightPosition); //设置光源在场景中的位置
 //启用光
 glEnable(GL_LIGHT0);
}
//绘制单位立方体
void DrawCube(float xPos,float yPos,float zPos)
{
 glPushMatrix();
  glTranslatef(xPos,yPos,zPos);
  glBegin(GL_QUADS);    //顶面
  glNormal3f(0.0f,1.0f,0.0f);
  glVertex3f(0.5f,0.5f,0.5f);
  glVertex3f(0.5f,0.5f,-0.5f);
  glVertex3f(-0.5f,0.5f,-0.5f);
  glVertex3f(-0.5f,0.5f,0.5f);
  glEnd();
  glBegin(GL_QUADS);    //底面
  glNormal3f(0.0f,-1.0f,0.0f);
  glVertex3f(0.5f,-0.5f,0.5f);
  glVertex3f(-0.5f,-0.5f,0.5f);
  glVertex3f(-0.5f,-0.5f,-0.5f);
  glVertex3f(0.5f,-0.5f,-0.5f);
  glEnd();
  glBegin(GL_QUADS);    //前面
  glNormal3f(0.0f,0.0f,1.0f);
  glVertex3f(0.5f,0.5f,0.5f);
  glVertex3f(-0.5f,0.5f,0.5f);
  glVertex3f(-0.5f,-0.5f,0.5f);
  glVertex3f(0.5f,-0.5f,0.5f);
  glEnd();
  glBegin(GL_QUADS);    //背面
  glNormal3f(0.0f,0.0f,-1.0f);
  glVertex3f(0.5f,0.5f,-0.5f);
  glVertex3f(0.5f,-0.5f,-0.5f);
  glVertex3f(-0.5f,-0.5f,-0.5f);
  glVertex3f(-0.5f,0.5f,-0.5f);
  glEnd();
  glBegin(GL_QUADS);    //左面
  glNormal3f(-1.0f,0.0f,0.0f);
  glVertex3f(-0.5f,0.5f,0.5f);
  glVertex3f(-0.5f,0.5f,-0.5f);
  glVertex3f(-0.5f,-0.5f,-0.5f);
  glVertex3f(-0.5f,-0.5f,0.5f);
  glEnd();
  glBegin(GL_QUADS);    //右面
  glNormal3f(1.0f,0.0f,0.0f);
  glVertex3f(0.5f,0.5f,0.5f);
  glVertex3f(0.5f,-0.5f,0.5f);
  glVertex3f(0.5f,-0.5f,-0.5f);
  glVertex3f(0.5f,0.5f,-0.5f);
  glEnd();
 glPopMatrix();
}
//处理场景的绘制
void Render()
{
 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //清理颜色/深度缓存
 glLoadIdentity();     //复位旋转角度计数器
 angle=angle+0.1f;     //递增旋转角度计数器
 if(angle>=360.0f)     //假设已旋转一周,复位计数器
  angle=0.0f;
 glTranslatef(0.0f,0.0f,-3.0f);
 glRotatef(angle,1.0f,0.0f,0.0f);
 glRotatef(angle,0.0f,1.0f,0.0f);
 glRotatef(angle,0.0f,0.0f,1.0f);
 DrawCube(0.0f,0.0f,0.0f);
 glFlush();       
 SwapBuffers(g_HDC);     //交换前后缓存
}
//为设备环境设置像素格式的函数
void SetupPixelFormat(HDC hDC)
{
 int nPixelFormat;
 static PIXELFORMATDESCRIPTOR pfd=
 {
  sizeof(PIXELFORMATDESCRIPTOR),
   1,
   PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
   PFD_TYPE_RGBA,
   32,
  0,0,0,0,0,0,
  0,
  0,
  0,
  0,0,0,0,
  16,
  0,
  0,
  PFD_MAIN_PLANE,
  0,
  0,0,0
 };
 nPixelFormat=ChoosePixelFormat(hDC,&pfd);
 SetPixelFormat(hDC,nPixelFormat,&pfd);
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
 static HGLRC hRC;
 static HDC hDC;
 int width,height;
 switch(message)
 {
 case WM_CREATE:
  hDC=GetDC(hwnd);
  g_HDC=hDC;
  SetupPixelFormat(hDC);
  hRC=wglCreateContext(hDC);
  wglMakeCurrent(hDC,hRC);
  return 0;
  break;
  
 case WM_CLOSE:
  wglMakeCurrent(hDC,NULL);
  wglDeleteContext(hRC);
  PostQuitMessage(0);
  return 0;
  break;
  
 case WM_SIZE:
  height=HIWORD(lParam);
  width=LOWORD(lParam);
  if(height==0)
   height=1;
  glViewport(0,0,width,height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(54.0f,(GLfloat)width/(GLfloat)height,1.0f,1000.0f);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  return 0;
  break;
 default:
  break;
 }
 return (DefWindowProc(hwnd,message,wParam,lParam));
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
 WNDCLASSEX windowClass;
 HWND hwnd;
 MSG msg;
 bool done;
 int width=800;
 int height=600;
 int bits=32;
 windowClass.cbSize=sizeof(WNDCLASSEX);
 windowClass.style=CS_HREDRAW|CS_VREDRAW;
 windowClass.lpfnWndProc=WndProc;
 windowClass.cbClsExtra=0;
 windowClass.cbWndExtra=0;
 windowClass.hInstance=hInstance;
 windowClass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
 windowClass.hCursor=LoadCursor(NULL,IDC_ARROW);
 windowClass.hbrBackground=NULL;
 windowClass.lpszMenuName=NULL;
 windowClass.lpszClassName="MyClass";
 windowClass.hIconSm=LoadIcon(NULL,IDI_WINLOGO);
 if(!RegisterClassEx(&windowClass))
  return 0;
 hwnd=CreateWindowEx(WS_EX_APPWINDOW|WS_EX_WINDOWEDGE,
  "MyClass",
  "OpenGL Cube",
  WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
  0,0,
  800,600,
  NULL,
  NULL,
  hInstance,
  NULL);
 if(!hwnd)
  return 0;
 ShowWindow(hwnd,SW_SHOW);
 UpdateWindow(hwnd);
 Initialize();  //初始化绘制环境
 done=false;
 while(!done)
 {
  PeekMessage(&msg,hwnd,NULL,NULL,PM_REMOVE);
  if(msg.message==WM_QUIT)
  {
   done=true;
  }
  else
  {
   Render();
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
 }
 return msg.wParam;
}

效果:



五 链接

http://blog.csdn.net/djl4104804/article/details/8131072
opengl库和函数具体解释

posted @ 2017-08-03 18:36  brucemengbm  阅读(3986)  评论(0编辑  收藏  举报