2012-02-01 164 views
2

我正在使用OpenGL/GLUT來實現Bresenham的線條繪製算法,並且出現了一些看似隨意的工件出現問題。這裏有一個例子:OpenGL線條繪製工件

This should be one line

下面是一些代碼,我認爲可能是相關的。我沒有包含填充頂點緩衝區的代碼,因爲我99%確定它是正確的並且已經重寫了它。問題出現了,我開始使用GLUT鼠標回調。

void Line::draw() 
{ 
    // Bind program and buffer 
    glUseProgram(program); 
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); 

    // Get position attribute location 
    GLuint vertexPosLoc = glGetAttribLocation(
           program, 
           "position"); 

    // Enable attribute 
    glEnableVertexAttribArray(vertexPosLoc); 

    // Associate vertex position with attribute 
    glVertexAttribPointer(vertexPosLoc, 2, GL_FLOAT, GL_FALSE, 0, 0); 

    glDrawArrays(GL_POINTS, 0, vertexDataSize); 

    // Reset the program 
    glDisableVertexAttribArray(vertexPosLoc); 
    glBindBuffer(GL_ARRAY_BUFFER, 0); 
    glUseProgram(0); 
} 



void display() 
{ 
    // Clear the color buffer and the depth buffer 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    vector<Line*>::iterator it; 
    for(it = lines.begin(); it < lines.end(); it++) 
    { 
     (*it)->draw(); 
    } 

    // Draw the temporary line 
    if(line) 
    { 
     line->draw(); 
    } 

    // Swap buffers 
    glutSwapBuffers(); 
} 

void mouseClick(int button, int state, int x, int y) 
{ 
    int viewVals[4]; 
    glGetIntegerv(GL_VIEWPORT, viewVals); 
    y = viewVals[3] - y; 
    if(button != GLUT_LEFT_BUTTON) 
    { 
     return; 
    } 
    if(state == GLUT_DOWN) 
    { 
     x1 = x; 
     y1 = y; 
    } 
    else 
    { 
     lines.push_back(line); 
     line = NULL; 
    } 

    glutPostRedisplay(); 
} 

void mouseMotion(int x, int y) 
{ 
    int viewVals[4]; 
    glGetIntegerv(GL_VIEWPORT, viewVals); 
    y = viewVals[3] - y; 

    // Delete the previous line 
    delete line; 

    // Create a new line 
    line = new Line(x1,y1,x,y); 
    line->setProgram(program); 

    glutPostRedisplay(); 
} 

這個想法是,你點擊一個點,線從該點到你釋放點。在我將這些功能與glutPostRedisplay()調用一起添加之前,線條繪圖似乎工作正常。

在上圖中,打算繪製的線是左邊的線。它的工作,但其他文物出現。它們也不在頂點緩衝區中,我檢查過了。

他們來自哪裏的任何想法?

回答

4

glDrawArrays()的第三個參數應該是個點的個數。你可能會傳遞一些花車嗎?

(這會導致你畫的兩倍多點,你打算,因爲在緩衝區中的每個頂點有兩個浮點值。加分將有垃圾值。)

+0

精彩。像魅力一樣工作。 – Kyle 2012-02-01 23:17:45