2012-09-04 29 views
1

我正在使用GLUtesselator填充一些非凸多邊形。如何釋放在GLU_TESS_COMBINE回調中分配的內存

它做得很不錯,但與一些多邊形它抱怨它需要一個結合功能,所以我提供了一個非常簡單的GLU_TESS_COMBINE回調,其分配一個新的頂點,只是複製COORDS(它是2D純色,所以我不需要內插RGB值或任何東西):

void CALLBACK tessCombine(GLdouble coords[3], GLdouble * vertex_data[4], GLfloat weight[4], GLdouble **outData) 
{ 
    GLdouble *vertex = new GLdouble[3]; 
    vertex[0] = coords[0]; 
    vertex[1] = coords[1]; 
    vertex[2] = coords[2]; 
    *outData = vertex; 
} 

現在一切都按預期呈現,但它顯然會泄漏內存。該文檔說:

分配另一個頂點,[0121]在調用gluTessEndPolygon之後的某個時間釋放內存。

但是在我找到的所有例子中,它們並沒有顯示如何處理內存。回調是免費的功能,無法釋放分配的內存,是嗎?

我能想到的唯一方法是將它們存儲在某個地方,然後自己刪除它們。這是正確的方法嗎?

回答

3

看看this OpenGL Tessellation tutorial

重點不是在回調中分配任何內存(否則你會得到內存泄漏)。相反,您應該將頂點數據複製到回調中的內存位置(因爲它在example中完成)。從您複製頂點數據的位置開始,由您決定。

這是回調函數看起來如何在他們example

void CALLBACK tessCombineCB(const GLdouble newVertex[3], const GLdouble *neighborVertex[4], 
          const GLfloat neighborWeight[4], GLdouble **outData) 
{ 
    // copy new intersect vertex to local array 
    // Because newVertex is temporal and cannot be hold by tessellator until next 
    // vertex callback called, it must be copied to the safe place in the app. 
    // Once gluTessEndPolygon() called, then you can safly deallocate the array. 
    vertices[vertexIndex][0] = newVertex[0]; 
    vertices[vertexIndex][1] = newVertex[1]; 
    vertices[vertexIndex][2] = newVertex[2]; 

    // compute vertex color with given weights and colors of 4 neighbors 
    // the neighborVertex[4] must hold required info, in this case, color. 
    // neighborVertex was actually the third param of gluTessVertex() and is 
    // passed into here to compute the color of the intersect vertex. 
    vertices[vertexIndex][3] = neighborWeight[0] * neighborVertex[0][3] + // red 
           neighborWeight[1] * neighborVertex[1][3] + 
           neighborWeight[2] * neighborVertex[2][3] + 
           neighborWeight[3] * neighborVertex[3][3]; 
    vertices[vertexIndex][4] = neighborWeight[0] * neighborVertex[0][4] + // green 
           neighborWeight[1] * neighborVertex[1][4] + 
           neighborWeight[2] * neighborVertex[2][4] + 
           neighborWeight[3] * neighborVertex[3][4]; 
    vertices[vertexIndex][5] = neighborWeight[0] * neighborVertex[0][5] + // blue 
           neighborWeight[1] * neighborVertex[1][5] + 
           neighborWeight[2] * neighborVertex[2][5] + 
           neighborWeight[3] * neighborVertex[3][5]; 


    // return output data (vertex coords and others) 
    *outData = vertices[vertexIndex]; // assign the address of new intersect vertex 

    ++vertexIndex; // increase index for next vertex 
} 
+0

有一個很好的例子好文章!我已經結束了將新頂點存儲在向量中,但它幾乎相同。謝謝 – MikMik

+0

順便說一句,不應該文件顯示正確的例子,而不是泄漏內存? – MikMik

+2

@MikMik是的,他們應該,但在文檔中,我不認爲他們分配內存。它看起來像這樣:'VERTEX * new = new_vertex();',我相信他們不會在new_vertex()函數中分配新的內存。 –