我正在尝试使用opengl(3.0)渲染球体。下面的算法计算顶点和相应的索引。总而言之,它运作得很好,然而,矩阵中似乎有一个小故障,因为我在球体内部得到一个丑陋的锥体。
vertices.resize(rings * segments * 3);
colors.resize(rings * segments * 3);
indices.resize(6 * rings * segments);
auto v = vertices.begin();
auto c = colors.begin();
auto i = indices.begin();
auto dTheta = M_PI / (f32)rings;
auto dPhi = 2 * M_PI / (f32)segments;
for ( u32 ring = 0; ring < rings; ++ring ) {
auto r0 = radius * sinf(ring * dTheta);
auto y0 = radius * cosf(ring * dTheta);
for ( u32 segment = 0; segment < segments; ++segment ) {
auto x0 = r0 * sinf(segment * dPhi);
auto z0 = r0 * cosf(segment * dPhi);
*v++ = x0; *c++ = color.r;
*v++ = y0; *c++ = color.g;
*v++ = z0; *c++ = color.b;
if (ring < rings) {
*i++ = ( (ring ) * segments ) + segment;
*i++ = ( (ring+1) * segments ) + segment;
*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring ) * segments ) + segment + 1;
*i++ = ( (ring ) * segments ) + segment;
}
}
}
知道我错过了什么吗?
答案 0 :(得分:3)
*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring+1) * segments ) + segment + 1;
*i++ = ( (ring ) * segments ) + segment + 1;
如果segment
等于segments - 1
,您会计算什么索引?是的,您从 next 段获得索引。
如果 没有下一个片段?然后你会在你的积分列表之外得到一个索引。
您的分段增量需要回绕到0:
*i++ = ( (ring+1) * segments ) + (segment + 1) % segments;
*i++ = ( (ring+1) * segments ) + (segment + 1) % segments;
*i++ = ( (ring ) * segments ) + (segment + 1) % segments;
另外,请考虑如果ring
等于rings - 1
会发生什么。同样的问题,但你需要一个不同的解决方案。您的if
声明有误。它应该是:
if((ring + 1) < rings)