2018年3月12日 星期一

Week03 ㄩㄐ的疲憊日常

Week03教學內容

(1)複習:重寫GLUT範例



開啟新專案(New Project),並確認會使用glut設定


練習打一次白色茶壺的Glut程式碼


#include <GL/glut.h> /*使用GLUT外掛*/
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /*顏色與深度(DEPTH)*/

    glutSolidTeapot(0.3); /*在僅有的300*300像素空間,將茶壺的大小變成原本的0.3倍*/

    glutSwapBuffers(); /*交換畫面buffer便會顯示*/
}


int main(int argc, char**argv) /*main() 參數進階版(個數,字串)*/

{
    glutInit(&argc, argv); /*進階參數,初始GLUT*/
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week03_MousePlay"); /*視窗名稱。建議不使用中文*/

    glutDisplayFunc(display);

    //glutMouseFunc(mouse); /*等等會使用的第一部分*/
    //glutMotionFunc(motion); /*第二部分*/

    glutMainLoop(); /*主要迴圈*/


}


能這樣打出來真是讓人感動萬分


再來是改變顏色的部分


#include <GL/glut.h>

void display()
{
    glClearColor(1, 1, 0, 1); /*黃色背景*/
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(0, 1, 0); /*茶壺填色*/    glutSolidTeapot(0.3);

    glutSwapBuffers();

}


int main(int argc, char**argv)

{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week03_MousePlay");

    glutDisplayFunc(display);

    //glutMouseFunc(mouse);
    //glutMotionFunc(motion);

    glutMainLoop();


}


打完以後理所當然應該要長這樣↓


又是一個感動萬分的部分




(2)滑鼠與鍵盤的應用


① 秀出點擊位置


在主程式和GLUT外掛中間新增函式


#include <stdio.h>

void mouse(int button, int state, int x, int y)
{
    printf("%d %d %d %d\n", button, state, x, y);
    /*在茶壺以及周圍點擊會出現座標*/

}



RUN點擊後↓


小黑區域會顯示點擊後的數據


另外一種的座標顯現方式是將函式內的printf("%d %d %d %d\n", button, state, x, y);

變為 if(state==GLUT_DOWN) printf("glVertex2f(%f, %f);\n", (x-150)/150.0, -(y-150)/150.0);

呈現的畫面如下↓


②移動/拖曳茶壺




#include <GL/glut.h>
float teapotX=0, teapotY=0; /*茶壺的位置*/
void display()
{
    //glClearColor(1, 1, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0); /*xyz參數*/
        glutSolidTeapot(0.3)
    glPopMatrix();

    glutSwapBuffers();

}

#include <stdio.h>

void mouse(int button, int state, int x, int y)
{
    if(state==GLUT_DOWN) printf("glVertex2f(%f, %f);\n", (x-150),150.0, -(y-150)/150.0);
}
void motion(int x, int y) /*茶壺的移動過程*/
{
    teapotX=  (x-150)/150.0;
    teapotY= -(y-150)/150.0; /*滑鼠位置改為茶壺位置*/
    printf("%d %d\n", x, y); /*印出移動的座標數據*/
    glutPostRedisplay();
}
int main(int argc, char**argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week03_MousePlay");

    glutDisplayFunc(display);

    glutMouseFunc(mouse); /*滑鼠偵測*/
    glutMotionFunc(motion); /*移動路徑偵測*/
    glutMainLoop();


}

沒有留言:

張貼留言