How to pass data from the vertex to the fragment shader in Metal
A step by step tutorial on implementing a MTKView in a UIView that passes data from the vertex function to the fragment function in a metal shader.
We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/metal/pass-data-within-shader branch.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Setup the MTKView
Follow the tutorial below to setup a MTKView within a UIView that shows a triangle.
Step Two: Update the Metal Shader
Update the metal shader to:
- Include a struct (VertexOut) that defines the data that will be passed from the vertex function to the fragment function. This struct must include a float4 position [[position]]; for the vertex function to have a valid return type.
- Update the return type of the vertex function to VertexOut.
- Create and return the VertexOut within the vertex function.
- Add the vertex out as an argument for the fragment function using code similar to VertexOut vertexOut [[stage_in]].
- Update the fragment function to use the data from the vertexOut.
Step Three: Test
Run the code on a device and confirm that you see a triangle similar to the one above.
Looking to learn more about things you can do with Swift, Metal and XCode ?
Search our blog to find educational content on learning how to use Swift, Metal and XCode.