在 OpenGL 中我得到了这个(缩短的代码)
void Mesh::CreateBuffer() {
glBindBuffer( GL_ARRAY_BUFFER, m_Buffers[POS_VB] );
glBufferData( GL_ARRAY_BUFFER, sizeof(Positions[0] /*vec3*/) * iVerticeNum, &Positions[0], GL_STATIC_DRAW );
glEnableVertexAttribArray( POSITION_LOCATION );
glVertexAttribPointer( POSITION_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, 0 );
// Fill index buffer.
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_Buffers[INDEX_BUFFER] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices[0] /*unsigned int*/) * iIndiceNum, &Indices[0], GL_STATIC_DRAW );
}
void Mesh::Render() {
// bind vertex arrays here!
.....
glDrawElements( GL_TRIANGLES, this->NumIndices, GL_UNSIGNED_INT, 0);
....
}
上面的代码在我的引擎中运行良好。但是当我决定将它移植到 Metal API 时,我遇到了一些问题——它只使用索引数据渲染模型的一半,它的网格中没有组,它只是简单的网格。但是当我尝试使用顶点数据( drawPrimitives )渲染它时,它渲染得很好。
这是我用来初始化和渲染我的网格的金属代码:
INIT
....
// Initialize mesh.
MetalMesh mesh;
mesh.vertexBuffer = [MetalDataBase->device newBufferWithBytes:Positions/* Vertice data */
length:sizeof(vec3) * iNumVertices
options:MTLResourceOptionCPUCacheModeDefault];
mesh.indexBuffer = [MetalDataBase->device newBufferWithBytes:Indices
length:sizeof(unsigned int) * iNumIndices
options:MTLResourceOptionCPUCacheModeDefault];
DRAW
// Drawing..
[MetalDataBase->commandEncoder setVertexBuffer:metalResource->metalMeshes[index].vertexBuffer offset:0 atIndex:0];
// DrawPrimitives renders mesh **fine**, as it should.
//[MetalDataBase->commandEncoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:iVerticeNum];
// But it doesn't, it just renders half of model,
// while **iIndiceNum** is right number with its data.
[MetalDataBase->commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:iIndiceNum indexType:MTLIndexTypeUInt32 indexBuffer:metalResource->metalMeshes[index].indexBuffer indexBufferOffset:0];