Group Group Group Group Group Group Group Group Group Forums

iOS Metal Tutorial with Swift Part 4: Lighting

In this iOS Metal tutorial, learn how to implement the Phong lighting model into a Metal app.

This is a companion discussion topic for the original entry at

I followed through this series, than I have written one more class to load a mesh from an obj file. Now I have an application that draws meshes correctly, but there is a problem with it. Somewhere around 400 vertices it starts to throw fps. (with 423 v has 25 fps) and after that I start getting CrashReports from the GPU about restarting and it keeps looping until I restart the device. I know that I can not have unlimited vertices and faces but that number is a bit too small, isn’t it?
Do you have any idea how can I optimise it?


can this be updated for spritekit, swift 3+ and Xcode 8+?

@haawa, after completing part 4, my FPS dropped to 10. Is this normal? I would think the GPU could handle this no problem. The utilization is at 100% and frame time for GPU is over 100ms. Just checking if this is normal before I start combing through my code. Thanks!

I should note that it was after the specular lighting was added. Before that I was getting 60 FPS.

So I found the culprit. In Part 2 of this series we added the following line to Node.swift.

renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: vertexCount, instanceCount: vertexCount/3)
  • In Part 1 we used instanceCount: 1.
  • In Part 2 we refactored to instanceCount: vertexCount/3.
  • In Part 4 the value of vertexCount/3 is 12! This caused the frame rate to drop.

The finished example uses a different drawPrimitives.

renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount)

This method defaults instanceCount to 1, per the documentation. So you can specify instanceCount: 1 in drawPrimitives or use the above method. Now it runs at a smooth 60 FPS.