gpt4 book ai didi

c++ - 如何释放在 GLU_TESS_COMBINE 回调中分配的内存

转载 作者:行者123 更新时间:2023-11-30 03:00:16 30 4
gpt4 key购买 nike

我正在使用 GLUtesselator 填充一些非凸多边形。

它工作得很好,但是对于一些多边形,它提示它需要一个组合函数,所以我提供了一个非常简单的 GLU_TESS_COMBINE 回调,它分配一个新顶点并只复制坐标(它是 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;
}

现在一切都按预期呈现,但它显然会泄漏内存。文档说:

Allocate another vertex, [...] Free the memory sometime after calling gluTessEndPolygon.

但在我找到的所有示例中,它们都没有显示如何处理内存。回调是自由函数,没有办法释放那里分配的内存,是吗?

我能想到的唯一方法是将它们存储在某个地方,然后自己删除它们。这是正确的方法吗?

最佳答案

查看 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
}

关于c++ - 如何释放在 GLU_TESS_COMBINE 回调中分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258404/

30 4 0