2013-03-30 36 views
2

我有一個OpenGL程序通過點擊鼠標來繪製一個圓。該程序工作正常,除非我試圖畫出前一個圓圈消失的多個圓圈。以下是代碼:使用C在OpenGL中繪製多個對象

#include <GL/glut.h> 
#include<math.h> 
#include<stdio.h> 
struct position 
{ 
    float x; 
    float y; 
}; 
typedef struct position Position; 

Position start; 
Position finish; 

void setPixel(int x, int y) 
{ 
    glBegin(GL_POINTS); 
    glVertex2f(x, y); 
    glEnd(); 
} 

void circle(int a0, int b0, int a1, int b1) 
{ 
    int i, x, y, x1, y1, r, p; 

    x1 = (a0+a1)/2; 
    y1 = (b0+b1)/2; 

    r = sqrt((((a1-x1)*(a1-x1))+((b1-y1)*(b1-y1)))); 

    p = (5/4-r); 
    x = 0; 
    y = r; 
    while(x <= y) 
    { 
     setPixel(x+x1, y+y1); 
     setPixel(x+x1, -y+y1); 
     setPixel(-x+x1, -y+y1); 
     setPixel(-x+x1, y+y1); 
     setPixel(y+x1, x+y1); 
     setPixel(y+x1, -x+y1); 
     setPixel(-y+x1, -x+y1); 
     setPixel(-y+x1, x+y1); 

     x = x+1; 
     if (p<0) 
      p = p+2*x+1; 
     else { 
      y = y-1; 
      p = p+2*x-2*y+1; 
     } 
    } 
} 

void display() 
{ 
    glClear(GL_COLOR_BUFFER_BIT); 

    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 

    glPushMatrix(); 

    circle(start.x, start.y, finish.x, finish.y); 

    glPopMatrix(); 

    glutSwapBuffers(); 
} 

void reshape(int w, int h) 
{ 
    glViewport(0, 0, w, h); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(0, w, h, 0, -1, 1); 
} 

void mouse(int button, int state, int x, int y) 
{ 
    switch(button) 
    { 
     case GLUT_LEFT_BUTTON: 

      if(state == GLUT_DOWN) 
      { 
       start.x = x; //x1 
       start.y = y; //y1 
      } 

      if(state == GLUT_UP) 
      { 
       finish.x = x; //x2 
       finish.y = y; //y2 
      } 
      break; 

      glutPostRedisplay(); 
    } 
} 

void motion(int x, int y) 
{ 
    finish.x = x; 
    finish.y = y; 
    glutPostRedisplay(); 
} 

int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); 
    glutInitWindowSize(640, 480); 
    glutInitWindowPosition(100, 100); 
    glutCreateWindow(""); 
    glutMouseFunc(mouse); 
    glutMotionFunc(motion); 
    glutDisplayFunc(display); 
    glutReshapeFunc(reshape); 

    glutMainLoop(); 
    return 0; 
} 

如何將多個圖像一起顯示?

+0

'glutPostRedisplay();'在switch-case中看起來不可達的代碼 –

+0

我檢查了它。這不是問題。實際上,glutPostRedisplay()不應該在那裏。我的錯誤 – user2227497

回答

4

如果你想繪製多個東西,然後繪製多個東西。你只畫一個圓圈。如果你改變了該圓的位置,它將被繪製在不同的地方。

但是我真的不會推薦在GL中這樣繪製。使用固定功能管線繪製單個像素爲GL_POINTS效率極低。 GL不是作爲光柵繪圖API設計的。

+0

您好JasonD,我也面臨這個問題。我在Android的OpenGLES2.0中開發了Autocad應用程序。我的問題是,我可以同時繪製多行和多個圓圈.App運行在Google Nexus7 Good.But中,當我在Samsung Galaxy Note II中運行我的應用程序時,我不能繪製多條線。當我畫一條線時,以前的線會自動擦除。這是我的Problem.just看到這個鏈接,它也包含示例代碼也..如果可能請幫助我.. http://stackoverflow.com/questions/17229066/is-opengl-development-gpu-dependant/17230475?noredirect= 1#17230475 – harikrishnan