2018年3月19日 星期一

Week 04 陳泓丞第四周學習內容

**期中考占80的重點程式碼**

glPushMatrix(); ///備份矩陣
    glTranslatef(x,y,z);///移動
    glRotatef(angle,x,y,z);///ˊ轉動
    glScalef(x,y,z);///縮放
    glBegin(GL_POLYGON);///開始畫
        glColor3f(r,g,b);///顏色
        glVertex3f(x,y,z);///頂點
    glEnd();///結束畫
glPopMatrix();///還原矩陣

NO.01  加入旋轉程式碼

#include<stdio.h>
#include<GL/glut.h>
float angle=0;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();///備份矩陣
        glRotatef(angle,0,0,1);///旋轉angle度
        glutSolidTeapot(0.3);
    glPopMatrix();///還原矩陣
    glutSwapBuffers();
    printf("%.1f\n",angle);
    angle++;///每次角度+1度
}
int main(int argc, char**argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week04 transformation");

    glutIdleFunc(display);///此函數是代表運算有空時才畫一圖形而旋轉,會視運算速度影響旋轉速度
    glutDisplayFunc(display);
    glutMainLoop();
}

NO.02 加入用滑鼠控制旋轉

#include<stdio.h>
#include<GL/glut.h>
float angle=0;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glRotatef(angle,0,0,1);
        glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
    ///printf("%.1f\n",angle);
    ///angle++;
}
void mouse(int button, int state, int x, int y)
{

}
void motion(int x, int y)
{///當mouse再拖曳motion時
    angle=x;///去改變angle值
    glutPostRedisplay();請畫面重畫
}
int main(int argc, char**argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week04 transformation");
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    ///glutIdleFunc(display);
    glutDisplayFunc(display);
    glutMainLoop();

}

NO.03  加入移動控制以及更新更好的程式

#include<stdio.h>

#include<GL/glut.h>
float angle=0, teapotX=0, teapotY=0;///加上移動座標
int oldX=0, oldY=0, nowRotate=0;///0: translate, 1: rotate
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0);///把轉完的茶壺再做移動
        glRotatef(angle,0,0,1);
        glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}
void mouse(int button, int state, int x, int y)
{
    if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) nowRotate=1;///如果是右鍵,就旋轉
    if(button==GLUT_RIGHT_BUTTON && state==GLUT_DOWN) nowRotate=0;///如果是左鍵,就移動
    oldX=x; oldY=y;///按下去時,把oldX,oldY記起來
}
void motion(int x, int y)
{
    if(nowRotate==1) angle += (x-oldX);///加上改變量
    else
    {
        teapotX += (x-oldX)/150.0;加上改變量
        teapotY += (oldY-y)/150.0;加上改變量
    }
    oldX=x; oldY=y;做完計算時,把oldX,oldY記起來
    glutPostRedisplay();
}
int main(int argc, char**argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week04 transformation");
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutDisplayFunc(display);
    glutMainLoop();

}

沒有留言:

張貼留言