0

I am creating a class that needs differently coded shaders due to varying inputs that are known at initialization. The goal would be that when the object is initialized the shader is also initialized and compiled into a library.

My problem is I have no clue how to write a .metal file to my apps directory like I see in XCode and frankly I am not sure iOS permissions will even let me do that. I think once I have the metal file in place it becomes easy but how?

The shader I hope to edit at compile time will have a variable amount of texture inputs based on the initialization parameters.

2 Answers 2

2

You don't write a .metal file. You create a MTLLibrary object directly from a string containing the shader program text.

You call either the -newLibraryWithSource:options:error: method or the -newLibraryWithSource:options:completionHandler: method of the MTLDevice protocol.

That said, either Matthijs's answer or some other approach may be more appropriate. For example, depending on which versions of iOS and which GPU family you're targeting, you may be able to use texture arrays with function constants to accommodate a variable number of textures. You should show a real example of the sort of shader you're hoping to build and how it may vary.

Sign up to request clarification or add additional context in comments.

Comments

2

Please look into the concept of "function constants".

You can define a value as a function_constant in your .metal file. Then when you create the function using the MTLLibrary you can pass in the actual value for these constants and Metal will compile a specialized version of your shader on-the-fly using these constant values.

3 Comments

I would do this except the shader needs to support a variable amount of textures as inputs. Will update question
Metal supports arrays of textures (and also something called texture arrays). Perhaps you could pass in this variable amount of textures using such an array?
Great idea unfortunately that only works with textures of the same size which does not work for my scenario

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.