How to structure variables & functionality in shared files in Metal
A guide for learning how to create shared Metal variables and functionality that can be used across Metal files in XCode.
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/shared-functionality branch.
git clone git@github.com:delasign/swift-starter-project.git
This tutorial first walks you through how to setup files to work independently (Step One) and then consolidates the functionality into a shared file to reduce code redundancy.
Step One: Setup the Project
Follow the tutorials below to learn how to create a polygons, with a color fill or with a variable line width.
Step Two: Create the Shared Files
In the folder that holds the shaders, create two new files:
- Shared.metal as a Metal Shader Source type.
- Shared.h as a Default - C Header type.
Step Three: Write the Shared Functionality
Write the shared functionality into the Shared.h and Shared.metal file.
- The Shared.h file should hold all the constants, structs and function definitions (not the actual functions).
- The Shared.metal file should include the Shared.h file at the top and should exclusively hold all the function definitions (i.e. the code within the functions defined in the Shared.h file).
Please note it is strongly recommended that both these files use the #pragma once mark to ensure that this header file is only included once.
Step Four: Include the Shared Header File in all Metal Files
In all Metal files that use the shared functionality, include the Shared.h file at the top of the file.
Please note that you must remove any functionality that is now shared from the metal file.
Step Five: Test
Run the code on a device and confirm that it works as expected.
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.