3
\$\begingroup\$

I want to develop a procedural galaxy / starfield generator.

A rather simple approach would be to use some pseudo-random algorithm to repeatedly create a star and its properties (such as position, mass, luminosity, density, and so on...). But in doing that, I would be quite limited in terms of the total number of stars. They would all be created at startup, and kept in memory, even the ones which are totally out of the player's range.

I do not want to end up with millions of star instances.

What I need is some way to only generate the stars which are near to the player and, therefore, being rendered. On the other side, I want the player to be able to return to stars, once they disappear due to being too far away. Take Space Engine for example, it also does not generate all its trillion stars at the start of the simulation.

What would be a suitable approach to this kind of problem?

\$\endgroup\$
5
\$\begingroup\$

Divide your universe into cubic chunks. You only generate the chunks around the player. When the player moves, release the memory occupied by the chunks further away from the player.

Generate the stars and other objects in each chunk with a pseudorandom number generator which you seed with the coordinates of the chunk. Using the same seed will result in the same sequence of random numbers. That means you can re-generate each chunk again and again and it will always turn out exactly the same.

If you want to render and calculate further away chunks with a lower level of detail (like only the stars for far away chunks, planets for closer chunks, asteroids and ships for the chunk the player is in or adjacent to), have your chunk generation algorithm generate the low-detail things first and the high-detail things later. That way you can execute the generation algorithm only to a certain level of detail and continue running it for more details when the player comes closer.

All you need to keep stored are any changes the player's activities caused to a chunk. When this becomes too much data to handle, consider saving the state of unloaded chunks to the hard drive. When you unload a chunk, save its state to a file. Read and re-apply the change-file for the chunk when the player returns.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.