Search code examples
iosswiftmetal

access swift Struct or class in Metal File


In swift file, vertex data was declared:

struct Vertex {
    let position: vector_float4
    let color: vector_float4
}

I want to access this struct in metal file, is it possible? if it is, how to make it?

I already know how to make it by Objective-C, just want to use swift.


Solution

  • It's not possible to use the Swift struct directly from Metal. However, you could declare the struct in an Objective-C header and use it (via an Objective-C bridging header) in both Swift and Metal. Consult the Metal Game template provided with Xcode for an example of how to do this. Contrary to Apple's best practice recommendations, I actually prefer not to do this, and instead declare such structures in each of the respective languages.

    The equivalent struct declaration in Metal Shading Language is

    struct Vertex {
        float4 position;
        float4 color;
    };
    

    If you're using a vertex descriptor in your pipeline (with a stage_in parameter to the vertex function, as opposed to doing manual vertex fetch by taking in a vertex_id and a pointer to Vertex structs), you'll need to add attribute attributes to the struct, corresponding to their indices in the vertex descriptor attributes array. For example,

    struct Vertex {
        float4 position [[attribute(0)]];
        float4 color [[attribute(1)]];
    };