Skip to content

Introducing the Metal framework

The Metal framework that was announced at WWDC 2014 for iOS and at WWDC 2015 also for OS X and tvOSMetal is an interface for programming the Graphics Processing Unit (GPU) in your computer. The main advantages of using Metal are:

  • provides the lowest overhead access to the GPU, hence it reduces all bottlenecks usually caused by data transferring between the CPU and GPU in other frameworks.
  • provides up to 10 times the number of draw calls compared to OpenGLMetal, however, is not cross-platform like OpenGL is, so it is not meant to be a replacement for OpenGL.
  • allows to also run compute applications with performance levels comparable to similar technologies such as CUDA or OpenCL.
  • has a custom shader language that allows shaders precompiling so they are a lot faster at run time.
  • has built-in memory and resource management particularized to these platforms.

Since Metal does not run in the Xcode simulator and since we cannot assume all our readers have an iOS device that has an A7 processor or newer, we will rather create an OS X project instead. In Xcode create a Cocoa Application. In the storyboard, drag and drop a Label onto the View Controller. Center it, enlarge it, to make sure we can display 2 lines of text. Set necessary constraints. Your storyboard should look like this:

Next, go to ViewController.swift and create an IBOutlet for the label we just created. You can name it simply label or anything else you wish. Finally, let’s write some code. Your class should look like this:

Let’s go over the code above. First we need to import Metal because we are calling the MTLCopyAllDevices() function which belongs to the Metal framework. However, since Cocoa already imports Metal and the AppKit framework which lets us use classes such as NSViewController, we don’t need another import line just for Metal.

Then, inside viewDidLoad() is where all the magic happens. We create a Metal device by calling MTLCopyAllDevices() and then we simply query for its name so we can display it as the label text. Note that MTLCopyAllDevices() is only available in OS X. For iOS/tvOS devices use MTLCreateSystemDefaultDevice() instead. A device is an abstraction of the GPU and provides us a few methods and properties, such as name which we used above.

If you run the project, you should be able to see the following output:

There is not much to see but for now you learned how to “talk” to the GPU at the lowest possible level. The source code for this article is on Github.

Until next time!

Leave a Reply

Your email address will not be published. Required fields are marked *