天天看點

glutSolidSphere 用例

glutSolidSphere是GLUT工具包中的一個函數,該函數用于渲染一個球體。球體球心位于

原點。在OpenGL中預設的原點就是視窗客戶區的中心。

1 怎麼将球體進行移動?

可以使用glPushMatrix,glPopMatrix儲存一個移位矩陣,就可以移動球體

    glPushMatrix();

    glTranslatef(1.0, 0.0, 0.0);

    GLfloat mat_ambient[] = { 0.021500, 0.174500, 0.021500, 0.550000};

    GLfloat mat_diffuse[] = { 0.075680, 0.614240, 0.075680, 0.550000};

    GLfloat mat_specular[] = { 0.633000, 0.727811, 0.633000, 0.550000 };

    GLfloat mat_shininess[] = { 76.800003}; //材質RGBA鏡面指數,數值在0~128範圍内

    glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);

    glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);

    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);

    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);

    glutSolidSphere (1.0, 40, 50);    //半徑為 1,40 條緯線,50 條經線

    glPopMatrix();

    glFlush (); 

2 已經設定材質,光照,球體還是黑色的平面圖?

必須設定投影矩陣,建立裁剪的矩陣區域,才能夠看到立體,這時候需要調用glOrtho

/* 定義 GLUT 的 reshape 函數,w、h 分别是輸出圖形的視窗的寬和高*/ 

void reshape (int w, int h) 

  glViewport (0, 0, (GLsizei) w, (GLsizei) h); 

  glMatrixMode (GL_PROJECTION); 

  glLoadIdentity ( ); 

  if (w <= h) 

    glOrtho (-1.5, 1.5, -1.5 * ( GLfloat ) h / ( GLfloat ) w, 

    1.5* ( GLfloat ) h / ( GLfloat ) w, -10.0, 10.0 ); //建立平行視景體

  else 

    glOrtho (-1.5 * ( GLfloat ) w / ( GLfloat ) h,1.5 * ( GLfloat ) 

    w/( GLfloat ) h, -1.5, 1.5, -10.0, 10.0); 

  glMatrixMode ( GL_MODELVIEW ); 

  glLoadIdentity ( ) ; 

代碼

# include < GL/glut.h > 

/* 初始化材料屬性、光源屬性、光照模型,打開深度緩沖區等 */ 

void init(void) 

  GLfloat light_position [ ] = { 0., 1.5, 1.5, 0.0 }; 

  glClearColor ( 0.0, 0.0, 1.0, 0.0 ); //設定背景色為藍色

  glShadeModel ( GL_SMOOTH ); 

  glLightfv ( GL_LIGHT0, GL_POSITION, light_position); 

  glEnable (GL_LIGHTING); 

  glEnable (GL_LIGHT0); 

  glEnable (GL_DEPTH_TEST); 

/*調用 GLUT 函數,繪制一個球*/ 

void display ( void ) 

  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

  {

    GLfloat mat_shininess[] = { 76.800003}; //材質RGBA鏡面指數,數值在0~128範

圍内

  }

    glTranslatef(-1.0, 0.0, 0.0);

    GLfloat mat_ambient[] = {  0.247250, 0.199500, 0.074500, 1.000000};

    GLfloat mat_diffuse[] = { 0.751640, 0.606480, 0.226480, 1.000000};

    GLfloat mat_specular[] = { 0.628281, 0.555802, 0.366065, 1.000000 };

    GLfloat mat_shininess[] = { 51.200001}; //材質RGBA鏡面指數,數值在0~128範

  glFlush (); 

int main(int argc, char** argv) 

  glutInit (&argc, argv);     // GLUT 環境初始化

  glutInitDisplayMode (GLUT_SINGLE |GLUT_RGB |GLUT_DEPTH); // 顯示模式初始化

  glutInitWindowSize (300, 300);       // 定義視窗大小

  glutInitWindowPosition (100, 100);   // 定義視窗位置  

  glutCreateWindow ( argv [ 0 ] );   // 顯示視窗,視窗标題為執行函數名

  init( );

  glutDisplayFunc ( display );  // 注冊 OpenGL 繪圖函數(一種特殊的調用方式,下

同) 

  glutReshapeFunc ( reshape );   // 注冊視窗大小改變時的響應函數

  glutMainLoop( );      // 進入 GLUT 消息循環,開始執行程式

  return 0; 

    本文轉自fengyuzaitu 51CTO部落格,原文連結:http://blog.51cto.com/fengyuzaitu/1894968,如需轉載請自行聯系原作者

繼續閱讀