“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

An overview of the

During Metal development, we may customize several.metal files for functionality. We may also output the SDK to the user to call.

At this point, the following problems will be encountered:

  1. Too many. Metal files, resulting in the SDK file increase, difficult to manage.
  2. The exposed.metal reveals some algorithmatic logic that we might not want the user to see.

Is there a good solution? The answer is yes, we can pack multiple. Metal files into a single. Metallib file.

This article will show you how to compile the Metal Shading Language source code and generate the Metal library from the command line without using Xcode.

Run commands to build the library

Metal Command parameters

The following are the parameters of the Metal command line. Type in terminal

xcrun -sdk macosx metal -help 
Copy the code

or

xcrun -sdk iphoneos metal -help 
Copy the code

To view help information.

To form intermediates

use

xcrun -sdk macosx metal MyLibrary.metal -o MyLibrary.air
Copy the code

Command to compile a single.metal file into an.air file. The air file stores the middle code of Metal Shading Language source code.

For multiple. Air files, we can use the metal-ar tool to compress multiple. Air files into a. Metalar file (metal-AR is similar to AR in UNIX).

Generate library file

Use the metallib tool directly to merge multiple.air files or.metalar files into a single.metallib file.

The.metalar file is just an intermediate file that will eventually be merged into.metallib.

You can do this by using the following command:

xcrun -sdk macosx metallib MyLibrary.air -o MyLibrary.metallib
Copy the code

Load and use library files

After building a library using Metal’s command line tool, you need to add the generated.metallib file to your Xcode project. You then call the makeLibrary(filepath:) method as the MTLLibrary to load the library you just generated.

guard let libraryFile = Bundle.main.path(forResource: "MyLibrary", 
ofType: "metallib") else { return }
do { 
    let myLibrary = try device.makeLibrary(filepath: libraryFile)
  } catch let error { 
        print("Library error: \(error.localizedDescription)")
  }
Copy the code

MTLLibrary is a collection of Metal shader functions. To load a precompiled library, call the following method:

  • makeDefaultLibrary()
  • makeLibrary(filepath:)
  • makeLibrary(data:)

To load a run-time compiled library, call the following method:

  • makeLibrary(source:options:completionHandler:)
  • makeLibrary(source:options:)

conclusion

This article describes how to compile the Metal Shading Language source code and generate the Metal library from the command line without using Xcode and how to load the generated library.