Thursday, September 4, 2014

17. Particle System


       This is the beginnings of the Cyclone Game Engine's particle system. It is mostly a 3D particle system implemented by using point sprites. It animates the particles entirely on the graphics card by using a custom vertex shader, so that it can draw large numbers of particles with minimal CPU overhead.

       When displaying large numbers of particles, games can easily become bottle-necked by the amount of CPU work involved in updating everything and transferring the latest particle positions across the GPU for drawing. The game engine avoids that by animating the particles entirely on the GPU, so the CPU overhead remains low regardless of how many particles are active. By moving things to the GPU, it leaves the CPU free for many other things such as gameplay, physics and or Artificial Intelligence.

       When a new particle is created, the CPU fills a vertex structure with the position, velocity, and creation time. After this vertex is uploaded to the GPU, the CPU never needs to touch it again. Every frame, the current time is set as a vertex shader parameter. When the GPU draws the particles, it can work out the age of each one by comparing the creation time (which is stored as part of the vertex data) with the current time. Knowing the starting position, velocity, and age, the shader can compute the position and draw a point sprite at this location.

       New particles are always added to the end of the vertex buffer, and old ones are removed from the start. Because all particles last the same amount of time, this means the active particles will always be grouped together in a consecutive region of the buffer, and so can all be drawn in a single call. The CPU is responsible for adding new particle vertices to the end of the buffer, and for retiring old ones from the start, but it doesn't need to do anything with the active particles in the middle of the buffer. Even games with thousands of particles typically only create and retire a few each frame, so the resulting CPU workload is very low. The Cyclone Game Engine's particle system can also be used for efficient 2D particles by setting an orthographic matrix as the camera projection.

       The video above is a demonstration of the particle system. The smoke is a 3D particle system where the game engine creates a giant plume of long lasting smoke. The fire is an animated 2D billboard sprite rendered in 3D, mostly done to save processing.



No comments:

Post a Comment