I am trying to create a framework that works with METAL Api (iOS). I am pretty new to this platform and I would like to know how to build the framework to work with .metal files
There are many ways to provide Metal shaders with a static library, all with different tradeoffs. I'll try to enumerate them here.
1) Transform your .metal files into static strings that are baked into your static library.
This is probably the worst option. The idea is that you preprocess your Metal shader code into strings which are included as string literals in your static library. You would then use the newLibraryWithSource:options:error:
API (or its asynchronous sibling) to turn the source into an MTLLibrary
and retrieve the functions. This requires you to devise a process for doing the .metal
-to-string conversion, and you lose the benefit of shader pre-compilation, making the resulting application slower.
2) Ship .metal files alongside your static library and require library users to add them to their app target
All things considered, this is a decent option, though it places more of a burden on your users and exposes your Metal shader source (if that's a concern). Code in your static library can use the "default library" (newDefaultLibrary
), since the code will be compiled automatically by Xcode into the app's default.metallib
, which is embedded in the app bundle as a resource.
3) Ship a .metallib file alongside your static library
This is a good middle ground between ease-of-use, performance, and security (since it doesn't expose your shader source, only its IR). Basically, you can create a "Metal Library" target in your project, into which you put your shader code. This will produce a .metallib
file, which you can ship along with your static library and have your user embed as a resource in their app target. Your static library can load the .metallib
at runtime with the newLibraryWithData:error:
or newLibraryWithURL:error:
API. Since your shaders will be pre-compiled, creating libraries will be faster, and you'll keep the benefit of compile-time diagnostics.