I made some progress! Or at least I think so, it is still unclear.
I simplified the shader code to not include the external library for now:
#include <metal_stdlib>
using namespace metal;
[[ stitchable ]] half4 checkerboard(float2 position, half4 currentColor, float size, half4 newColor) {
uint2 posInChecks = uint2(position.x / size, position.y / size);
bool isColor = (posInChecks.x ^ posInChecks.y) & 1;
return isColor ? newColor * currentColor.a : half4(0.0, 0.0, 0.0, 0.0);
}
I am going to deal with the missing library later.
Now the expanded shader compilation code looks as follows:
let shaderURL = Bundle.main.url(forResource: "shaders", withExtension: "txt")!
let source = try! String(contentsOf: shaderURL, encoding: .utf8)
do {
let device = MTLCreateSystemDefaultDevice()!
let opt = MTLCompileOptions()
opt.enableLogging = true
// Those two options are important.
opt.libraryType = .dynamic
opt.installName = "shaders.metallib"
// We need to create MTLLibrary...
let library = try device.makeLibrary(source: source, options: opt)
// ...that we convert into dynamic library...
let dynLib = try device.makeDynamicLibrary(library: library)
// ...that we can serialize to disk as metallib file...
let tempUrl : URL = .temporaryDirectory.appending(
component: dynLib.installName, directoryHint: .notDirectory)
try dynLib.serialize(to: tempUrl)
// ... that we can finally read as ShaderLibrary
let sLib = ShaderLibrary(url: tempUrl)
} catch {
//
}
One success is that now MTLLibrary builds successfully, I can confirm checkerboard function is there. So far so good!
ShaderLibrary constructor does not complain, but the problem is that it does not work when used in say .colorEffect - everything just hangs, and as I am using Playgrounds, debugging anything is impossible.