Search code examples
metal

Can I use [[stage_in]] signature with [[buffer(0)]] signature in Metal(MSL)?


Are the following MSL codes valid?

struct UniformBuffer
{
    float2 scale;
    float2 translate;
};

struct VertexInput
{
    float4 position [[ attribute(0) ]];
    float2 texcoord [[ attribute(1) ]];
    float4 color [[ attribute(2) ]];
};

struct VertexOutput
{
    //...
};

vertex VertexOutput main(constant UniformBuffer& ubo[[ buffer(0) ]], VertexInput input [[ stage_in ]])
{
    //...
}

If this code is valid, how should I specify the indices of the [[stage_in]] buffer and [[buffer(0)]] buffer when calling setVertexBuffer in Metal Application?

I tried to call the setVertexBuffer function based on the page at

https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515829-setvertexbuffer?language=objc,

but I am not sure what value to specify for atIndex is correct.


Solution

  • The shader itself is valid. stage_in in the vertex shader implies that you are going to use MTLVertexDescriptor that you set on MTLRenderPipelineDescriptor. MTLVertexDescriptor contains attributes and layouts. Those are arrays of other descriptors. The buffer indices the stage_in variable "pulls" the data from are specified by setting the bufferIndex on MTLVertexAttributeDescriptor. The only thing you need is to make sure that you use indices that you aren't using for buffer(i) bind points.