用金属索引绘图

时间:2016-09-07 10:49:00

标签: ios swift metal metalkit

我正在尝试加载模型(表单.OBJ)并使用MetalKit将其绘制到iOS上的屏幕上。问题是,我得到一些随机多边形而不是我的模型...... 以下是倾向于加载模型的代码(代码基于 raywenderlich.com 的教程:

        let allocator               = MTKMeshBufferAllocator(device: device)
        let vertexDescriptor        = MDLVertexDescriptor()
        let vertexLayout            = MDLVertexBufferLayout()
        vertexLayout.stride         = sizeof(Vertex)
        vertexDescriptor.layouts    = [vertexLayout]
        vertexDescriptor.attributes = [MDLVertexAttribute(name: MDLVertexAttributePosition, format: MDLVertexFormat.Float3, offset: 0, bufferIndex: 0),
                                       MDLVertexAttribute(name: MDLVertexAttributeColor, format: MDLVertexFormat.Float4, offset: sizeof(float3), bufferIndex: 0),
                                       MDLVertexAttribute(name: MDLVertexAttributeTextureCoordinate, format: MDLVertexFormat.Float2, offset: sizeof(float3)+sizeof(float4), bufferIndex: 0),
                                       MDLVertexAttribute(name: MDLVertexAttributeNormal, format: MDLVertexFormat.Float3, offset: sizeof(float3)+sizeof(float4)+sizeof(float2), bufferIndex: 0)]
        var error: NSError?
        let asset = MDLAsset(URL: path, vertexDescriptor: vertexDescriptor, bufferAllocator: allocator, preserveTopology: true, error: &error)
        if error != nil{
            print(error)
            return nil
        }

        let model = asset.objectAtIndex(0) as! MDLMesh
        let mesh  = try MTKMesh(mesh: model, device: device)

这是我的绘图方法:

    func render(commandQueue: MTLCommandQueue, pipelineState: MTLRenderPipelineState,drawable: CAMetalDrawable,projectionMatrix: float4x4,modelViewMatrix: float4x4, clearColor: MTLClearColor){

    dispatch_semaphore_wait(bufferProvider.availibleResourcesSemaphore, DISPATCH_TIME_FOREVER)

    let renderPassDescriptor = MTLRenderPassDescriptor()
    renderPassDescriptor.colorAttachments[0].texture = drawable.texture
    renderPassDescriptor.colorAttachments[0].loadAction = .Clear
    renderPassDescriptor.colorAttachments[0].clearColor = clearColor
    renderPassDescriptor.colorAttachments[0].storeAction = .Store

    let commandBuffer = commandQueue.commandBuffer()
    commandBuffer.addCompletedHandler { (buffer) in
        dispatch_semaphore_signal(self.bufferProvider.availibleResourcesSemaphore)
    }

    let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor)
    renderEncoder.setCullMode(MTLCullMode.None)

    renderEncoder.setRenderPipelineState(pipelineState)
    renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0)
    renderEncoder.setFragmentTexture(texture, atIndex: 0)
    if let samplerState = samplerState{
        renderEncoder.setFragmentSamplerState(samplerState, atIndex: 0)
    }


    var nodeModelMatrix = self.modelMatrix()
    nodeModelMatrix.multiplyLeft(modelViewMatrix)
    uniformBuffer = bufferProvider.nextUniformsBuffer(projectionMatrix, modelViewMatrix: nodeModelMatrix, light: light)
    renderEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, atIndex: 1)
    renderEncoder.setFragmentBuffer(uniformBuffer, offset: 0, atIndex: 1)
    if indexBuffer != nil{
        renderEncoder.drawIndexedPrimitives(.Triangle, indexCount: self.indexCount, indexType: self.indexType, indexBuffer: self.indexBuffer!, indexBufferOffset: 0)
    }else{
        renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: vertexCount, instanceCount: vertexCount/3)
    }
    renderEncoder.endEncoding()

    commandBuffer.presentDrawable(drawable)
    commandBuffer.commit()
}

这是我的顶点着色器:

struct VertexIn{
   packed_float3 position;
   packed_float4 color;
   packed_float2 texCoord;
   packed_float3 normal;
};

struct VertexOut{
    float4 position [[position]];
    float3 fragmentPosition;
    float4 color;
    float2 texCoord;
    float3 normal;
};

struct Light{
    packed_float3 color;
    float ambientIntensity;
    packed_float3 direction;
    float diffuseIntensity;
    float shininess;
    float specularIntensity;
};

struct Uniforms{
    float4x4 modelMatrix;
    float4x4 projectionMatrix;
    Light light;
};

vertex VertexOut basic_vertex(
                          const device VertexIn* vertex_array [[ buffer(0) ]],
                          const device Uniforms&  uniforms    [[ buffer(1) ]],
                          unsigned int vid [[ vertex_id ]]) {

   float4x4 mv_Matrix = uniforms.modelMatrix;
   float4x4 proj_Matrix = uniforms.projectionMatrix;

    VertexIn VertexIn = vertex_array[vid];

    VertexOut VertexOut;
    VertexOut.position = proj_Matrix * mv_Matrix * float4(VertexIn.position,1);
    VertexOut.fragmentPosition = (mv_Matrix * float4(VertexIn.position,1)).xyz;
    VertexOut.color = VertexIn.color;
    VertexOut.texCoord = VertexIn.texCoord;
    VertexOut.normal = (mv_Matrix * float4(VertexIn.normal, 0.0)).xyz;
    return VertexOut;
}

以下是它的样子:

link

实际上我有一个完全由我编写的其他类来加载模型。它工作正常,问题是它没有使用索引,所以我尝试加载比低多边形球更复杂的模型,GPU崩溃......无论如何我试图修改它以使用索引,我得到了同样的结果..比我添加硬编码索引进行测试,我得到了一个非常奇怪的结果。当我有3个索引它绘制了一个三角形,当我再添加3个时,它绘制了相同的三角形,经过3个顶点之后它绘制了2个三角形......

修改 这是我的Vertex结构:

struct Vertex:Equatable{
    var x,y,z: Float
    var r,g,b,a: Float
    var s,t: Float
    var nX,nY,nZ:Float

    func floatBuffer()->[Float]{
         return [x,y,z,r,g,b,a,s,t,nX,nY,nZ]
    }
}

1 个答案:

答案 0 :(得分:3)

我在这里看到了几个潜在的问题。

1)您的顶点描述符不会精确映射到您的Vertex结构。位置变量(x, y, z)占用12个字节,因此颜色变量从12个字节的偏移量开始。这与着色器的packed_float3 position结构中的VertexIn字段匹配,但在您提供给模型I / O的顶点描述符中,使用sizeof(Float3)(16)作为颜色的偏移量属性。因为您正在打包位置字段,所以您应该使用sizeof(Float) * 3代替此值,同样在后续偏移中使用strideof。我怀疑这是你问题的主要原因。

更一般地说,最好使用sizeof而不是MTLBuffer来说明对齐,但是 - 偶然 - 这在这里没有什么区别。

2)允许模型I / O使用单个offset来存储顶点和索引,因此在设置顶点缓冲区时应使用每个MTKMeshBuffer的{​​{1}}成员或者在每次绘制调用中指定索引缓冲区,而不是假设偏移量为0。