Calculating matrices on CPU takes up most of the frame time

Viewed 151

I am writing a simple engine for a simple game, so far I enjoy my little hobby project but the game grew and it now has roughly 800 of game objects at a time in a scene.

Every object, just like in Unity, has a transform component that calculates transformation matrix when the component is initialized. I started to notice that with 800 objects it takes 5.4 milliseconds just to update each matrix (for example if every object has moved) without any additional components or anything else.

I use GLKit math library, which for some reason faster than using native simd types. using simd types triples the time of calculation

here is a pice of code that runs it

    let Translation : GLKMatrix4 = GLKMatrix4MakeTranslation(position.x, position.y, position.z)
    let Scale : GLKMatrix4 = GLKMatrix4MakeScale(scale.x, scale.y, scale.z)
    let Rotation : GLKMatrix4 = GLKMatrix4MakeRotationFromEulerVector(rotation)
    
    //Produce model matrix
    let SRT = GLKMatrix4Multiply(Translation, GLKMatrix4Multiply(Rotation, Scale)) 

Question: I am looking for a way to optimize this so I can use more game objects. and utilize more components on my objects

1 Answers

There could be multiple bottlenecks in your program.

  1. Optimise your frame dependencies to avoid stalls as much as possible, e.g. by precomputing frame data on CPU. This is a good resource to learn about this technique.
  2. Make sure that all matrices are stored in one MTLBuffer which is indexed from your vertex stage
  3. On Apple silicon and iOS use MTLResourceStorageModeShared
  4. If you really want to scale to tens of thousands of objects, then compute your matrices in a compute shader to store them in an MTLBuffer. Then, use indirect rendering to issue your draw calls.
  5. In general, learn about AZDO.

Learn about compute shaders: https://developer.apple.com/documentation/metal/basic_tasks_and_concepts/performing_calculations_on_a_gpu

Learn about indirect rendering: https://developer.apple.com/documentation/metal/indirect_command_buffers

Related