2017年10月19日 星期四

翁驊成的學習筆記 week 06

week 06 實作


step 1.實作範例(打光)


#include <GL/glut.h>
#include "glm.h"

GLMmodel* pmodel = NULL;

void drawmodel(void)
{
    if (!pmodel) {
pmodel = glmReadOBJ("data/al.obj");
if (!pmodel) exit(0);
glmUnitize(pmodel);
glmFacetNormals(pmodel);
glmVertexNormals(pmodel, 90.0);
    }

    glmDraw(pmodel, GLM_SMOOTH | GLM_MATERIAL);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  //3D深度測試,清depth buffer才能正確繪圖

    drawmodel();
    glutSwapBuffers();
}

GLfloat pos[] = { 0.0, 0.0, -1.0, 0.0 };   //打光(3)

int main(int argc, char**argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);  //3D深度測試,要準備好depth buffer記憶體

    glutCreateWindow("week06");

    glutDisplayFunc(display);

    glEnable(GL_DEPTH_TEST);   //3D深度測試,打開Enable
    glEnable(GL_LIGHTING);   //打光(2),打開Enable
    glEnable(GL_LIGHT0);   //打光(1)打開Enable
    glLightfv(GL_LIGHT0, GL_POSITION, pos);

    glutMainLoop();
}



step 2.實作範例(轉動+移動)


#include <stdio.h>
#include <GL/glut.h>
#include "glm.h"

GLMmodel* pmodel = NULL;
int rotateX=0,rotateY=0,rotateZ=0;
int oldx=0,oldy=0;

void keyboard(unsigned char key, int x, int y)
{
    printf("Now : %c (%d %d)\n",key,x,y);
    if(key=='1')rotateX++;
    if(key=='2')rotateY++;
    if(key=='3')rotateZ++;
    glutPostRedisplay();
}

void mouse(int button, int state,int x, int y)
{
    printf("button:%d state:%d (%d %d)\n",button,state,x,y);

    if(state==GLUT_DOWN)
    {
        oldx=x;
        oldy=y;
    }
}

void motion(int x,int y)
{
    rotateY += -(x-oldx);
    rotateX += -(y-oldy);
    oldx=x;

    oldy=y;
    glutPostRedisplay();
}

void drawmodel(void)
{
    if (!pmodel)
    {
        pmodel = glmReadOBJ("data/al.obj");
        if (!pmodel) exit(0);
        glmUnitize(pmodel);
        glmFacetNormals(pmodel);
        glmVertexNormals(pmodel, 90.0);
    }

    glmDraw(pmodel, GLM_SMOOTH | GLM_MATERIAL);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //drawmodel();

    glPushMatrix();
    glRotatef(rotateX,1,0,0);
    glRotatef(rotateY,0,1,0);
    glRotatef(rotateZ,0,0,1);
    drawmodel();
    glPopMatrix();

    glutSwapBuffers();
}

GLfloat pos[] = { 0.0, 0.0, -1.0, 0.0 };

int main(int argc, char**argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week06");

    glutDisplayFunc(display);

    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutKeyboardFunc(keyboard);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0, GL_POSITION, pos);

    glutMainLoop();
}


沒有留言:

張貼留言