I’ve looked at using Metal kernel functions in the past for image processing. This post looks at them for a different purpose: calculating and rendering large particle systems.
Ordinarily, you may write a particle system where the particle logic (e.g. changing position and velocity) is executed on the CPU and then rendered on the GPU. Metal allows us to pass through an array of objects (e.g. particle value objects) and act upon individual array items in parallel much like a shader acts on individual pixels in an image. In fact, a Metal compute shader can do the particle maths and the rendering in one pass.
My MetalParticles project creates 250,000 particles which are all attracted towards a single gravity well. The user can touch the screen to move the gravity well and this change is illustrated with a transient grey circle.
Most of the hard work is done in my view controller and much of this code is borrowed from my reaction diffusion application. I have an array named particles that is populated with Particle structs: