Creating a procedurally generated universe, one algorithm at a time.

Let men burn stars

Posted on Dec 30, 2011

As promised last post, here’s a brief dev diary entry on creating random starfields and nebulas. After generating a passable looking planet the next step is to generate some cool looking  space for the planet to exist inside, and for that you need a couple of things.

Firstly you need a starfield. for this I created a spherical point cloud of star sprites centred about the camera. Getting a good even distribution of stars was a little trickier than I first thought it would be but I found a good algorithm for evenly distributing points about a sphere as shown below

StarParticle* p = 0;
HR(field->VertexBuffer->Lock(0, 0, (void**)&p, D3DLOCK_DISCARD));
for (int i=0;i<starCount;++i)
    StarParticle sp;
    float u = (((rand() % 10000)/(float)10000) - 0.5) * 2.0;
    float theta = ((rand() % 10000)/(float)10000) * 2 * D3DX_PI;

    float distance = (rand() % (int)(maxDistance-minDistance))+minDistance;
    //uniform distribution of points about a sphere
    sp.Position.x = (minDistance+distance) * sqrt(1-pow(u,2)) * cos(theta);
    sp.Position.y = (minDistance+distance) * sqrt(1-pow(u,2)) * sin(theta);
    sp.Position.z = (minDistance+distance) * u;
    sp.Size = (float)starDesc.Width * (1-(distance/maxDistance));
    p[i] = sp;

I also generate the star sprites procedurally by setting a size and start color in the center of a square, then as distance from the center increases, exponentially decaying the opacity. This produces sprites that look like this


When put together you get something like this (Note: I render the starfield’s into a cubemap skybox so that there’s no need to regenerate the skybox every single frame)


Now this is all well and good, but it does look very dull, and its also very hard to orient yourself as there are no recognizable landmarks. To fix this I added a number of extra detail layers. The first of these was two smooth background noise layers to add some lightness and variety to the background.



Finally I added a few layers of brighter stars of different colors and extra background star layers that were masked such that they were most visible around the nebula clouds to give the appearance of greater star density in the nebulas.


The results aren’t going to fool anyone into thinking its a Hubble photo, but I think they do look quite good. One thing that I haven’t yet implemented is a random palette picker to pick varied, yet complimentary colors for the nebula clouds to further increase variety. The palette picker can wait however as the next entry will be on the subject of generating random asteroid fields :)

Building steam with a grain of salt

Posted on Nov 13, 2011 graphics design proceduralcontent

Its been an insanely long time since this website has had an update, but I guess its better late than never. Anyways, about 3 months ago Junkship underwent a significant design refresh that was prompted by a few key factors. The first of these was the realization that as a small indie team, the scope and in particular the content creation required for the original Junkship concept was not really feasible. The second factor was a general disillusionment with hand crafted narratives and stories in games, and the desire to try a novel approach to narrative, and the third and final factor was an awesome game concept demo by Luke Smith that signalled a new and interesting direction that we could take Junkship in.

While I’m not going to go into any detail as to the specifics of the new gameplay (much of it is in flux anyway), one new aspect is that the game world will now be much more of a sandbox with an emphasis on procedurally generated content. The advantage of this are twofold, a sandbox arrangement allows the player the freedom to create their own narratives and stories, and procedural content allows the experiences of the player somewhat unique as well as reducing the content creation workload for us :)

So in order to facilitate this vision I’ve started off down the path of generating procedural space environments, and in fact the purpose of this post is to show the progress I’ve made thus far. The end goal is to procedurally generate solar systems with tens of planets, hundreds of moons and many thousands of asteroids, each of which have settlements and trade routes etc between them. While this is a fair way off, this end goal is simply the aggregation of a number of base content generators (a starfield generator, an earthlike planet generator, a rocky planet generator, an asteroid field generator, etc.)

I decided to start with the task of writing a generator for procedural earthlike planets. The basic idea was to use improved Perlin noise to generate a heightmap, which combined with a color gradient and a known sealevel I could produce a decent approximation of a planet with water oceans and continents. Below is the first iteration of this idea. To produce the terrain I used two layers of blended noise, the first was for the base continent terrain, and the second was a layer of ridged noise to produce mountain range like features. I also settled on using HLSL shaders on the GPU to do the heavy lifting as far as generating the terrain as the CPU proved too slow (10 seconds + per planet on the CPU compared with milliseconds on the GPU).


While the above screenshot is all well and good its got a long way before it looks properly earthlike. The next step was to calculate terrain normals from the generated heightmap to allow bumpmapping, as well as calculating specular terms for the water and terrain. Generating the normal map was relatively simple given that I already had all the height data and just had to record the height differences between adjacent texels to get what I wanted. The hardest part getting the bump mapping to actually work was due to me foolishly recording the bumpmap vectors in world space rather than the usual tangent space.


After producing a bumpmap like the one above (I also included a specular map in the alpha channel of the bumpmap, which you can’t see in the above image) I could now produce planets that looked like the one below.


The main problem I now had to overcome was to make sure the terrain had realistic variations in color. After staring at pictures of earth for hours I identified a few main techniques I could use in order to improve the terrain. The most obvious addition I could make was to ensure that the poles and areas with high altitude were snowy (and have a high specular value for more shininess). A more subtle variation on this is that forests and jungles are more common at lower altitudes and closer to the equator, with deserts being more common at higher altitudes and more extreme latitudes. Finally I could also vary terrain color based on the steepness of the terrain itself. By using two square color gradient textures and sampling/blending between them using the heightmap/normal map/texel latitude I was able to produce much better looking terrain.


The main feature I was now missing was clouds. I implemented these using two noise fields which I would additively blend together using a varying offset to simulate changing clouds over time. Getting the noise to look right was relatively easy, however I found the clouds really didn’t look right until they cast shadows on the terrain below them, once I did this the results were really good (especially when you see them changing with time).


One last thing I wanted to add was city lights on the night side of the planet (assuming of course that the planet is inhabited) to do this I used another noise map similar to the cloud layer and prioritized the intensity to areas more typically inhabited (i.e. near the coast and in the more comfortable latitudes).


After putting it all together…


Satisfied with the results so far, my next challenge was to generate random starfields and nebulas (of which the previous screenshot shows an early version), but that will have to wait for another post.

Creating empathy

Posted on Dec 31, 2010 design storytelling

Here’s a few thoughts of mine regarding player empathy in games. Its an old essay but I had forgotten about it until today when I did a clean out of my documents folder.

If a player is not involved in the emotional experience of a game and is instead seeing through to the machinery holding the game together, their actions become focused on beating the game and maximizing benefit to the character in the short term while disregarding the experience as a whole. The irony of this situation is that a linear medium can offer a greater emotional involvement as the player is railroaded into a particular experience. However this ignores the greatest aspect of interactive storytelling, namely for the player to shape the story as they see fit.

Due to the difficulties involved in creating truly meaningful non-linear storylines, designers cheat by commonly creating a set number of points in a story which diverge from the main story arc and give the illusion of non-linearity. However if the key decision points are noticeable by the player then the player will objectively weigh the decisions at a mechanical level removing them at an emotional level. For example given the choice between an easy and a hard path, players will often avoid the harder path, even if it means going against their opinions regarding the in-game events. As a designer it should be the goal to get the players involved in the story to the point where their emotions blind them to their "gamer sensibilities" in order to get them to take that hard path because they think its the "right" thing to do given the context of the story.

One way to stop the player viewing non-linear progression as a mechanical choice is to disguise the choice in such a way that the player cannot objectively make a choice outside of the context offered by the storyline itself. Simply put, if the player doesn’t see a "this makes my character evil +1" type decision they are more likely to make a decisions based at a truer emotional level. So what tools does a designer have available to them to aid in this process?

One such approach taken by Indigo prophecy is a time based approach. Dialog in Indigo prophecy is time based, the player has a limited time to make a decision on what to say, meaning they can’t dwell on the consequences of their decisions and instead have to make instinctive decisions. This time based approach to revealing a players personality could be extended further to events in the game world, for example: As a character in a collapsing mine shaft you are escaping with two other NPC’s. up ahead is a T intersection, one NPC goes one way, one NPC goes the other… who do you follow, if you hesitate you die - therefore you must make a spur of the moment decision.

The other approach is one taken by Final Fantasy VII with the gold saucer "date" sequence which I dub the "accumulative" approach. Throughout the earlier parts of the game the player is presented with a large number of seemingly unimportant decisions that are used by the game to evaluate which NPC you like the most. Then at the date scene that "favored" NPC takes part with you in a "date". This effectively reveals a players true preference through decisions which the player does not link to any important consequence, so they make them instinctively. Then at the point where a large decision has to be made, the game makes the choice based on the past decisions, denying the player an opportunity to jump out of character.

These two approaches work at very different time scales, and are useful for different situations. However the "accumulative" method is far more subtle and due to the fact that the decisions are spread throughout the game, the player cannot just reload and try the other option (which is possible with the timed decision approach). For this reason the accumulative method should be employed in situations where the player is most likely to try and "game" the system, as it essentially forces them to do what subconsciously they actually want to do. However, the accumulative method should be used with caution as the designer has to be sure that the intermediary decisions actually reveal the players mindset and preferences, otherwise the crucial decisions made by the game will appear frustrating or arbitrary to the player.

Asymmetrical gameplay

Posted on Dec 31, 2010 design

Okay, So I was watching the Zero punctuation left4Dead review the other day, and at one point Yahtzee mentions that while waiting to respawn as a special zombie in the humans vs zombies gameplay mode, he’d like to play as one of the normal zombies in the intervening time. This got me thinking, wouldn’t it be interesting if Valve released a free demo of left4Dead in which you could only play as the cannon fodder standard zombies in the game, so without buying the game you could still get a taste for the game, and at the same time you would be making the game more entertaining for people who actually bought the game.

Generalizing this idea wouldn’t it be interesting if more games were released with a free version which unlike standard demo’s allows you to take part in multiplayer action with people who bought the game, but you get to play in a less glamorous or entertaining role. Another example, World of Warcraft (or pretty much any other MMORPG for that matter) could release a free version where people can log in and play as monsters in the gameworld, obviously there’s no collecting items or stat progression to the monsters they play, but they get to fight players and paid subscribers get to have a greater challenge than fighting just the AI in PvE mode.

This could be a lucrative idea for certain games as you are essentially using the free players to provide a better experience for paying players, adding value with little expenditure on the developers part.

Subjectivity and perspective in games

Posted on Dec 31, 2010 design storytelling

Here’s an old essay of mine detailing how to allow game players to experience a game world subjectively, and what advantages this brings to interactive storytelling. Subjectivity is going to be a important part of the story telling technique used in Junkship.

Its pretty hard to deny that we all experience the world a little differently, it could be because we all see things from slightly different physical perspectives or more commonly that our perceptions of the same event are interpreted in a unique way by our minds as a function of our previous experiences, world view and belief systems. Even though we share common ground with others as to the nature of our experiences, there are subtle differences in how we react to and recollect situations that come together to give an internal model of external reality that not fully accessible to anyone but ourselves.

So what does this have to do with games and in particular role playing games (and in particular junkship :))? Well it has a lot to do with the RP in RPG, that is role playing, i.e putting yourself in someone else’s shoes and acting out a fantasy. This is made possible by our ability to simulate what we believe another being is experiencing within our own minds, we learn this from a young age and it is a key social skill that helps us understand the actions and thoughts of others. Our minds are sufficiently powerful to create almost a complete presence of mind for simple entities such as pets whereby we can tell almost exactly how they will behave in a given situation, however we are unable to completely understand the thought process going on within another human mind.

Traditionally western RPG’s leave characters as empty shells (an extreme example being games featuring a silent protagonist such as the half life series) and let the player fill them with their own presence of mind. In this way it is possible to display the world from a purely objective viewpoint to the player and for the player to react as they would as if the character were themselves. This approach works in situations where the character is not required by the story to have strong characterization.

Some RPG’s attempt to shoehorn the player into their character by crude statistical means such as ‘intelligence’ points for a character. for example a particular riddle cannot be solved by the player until their intelligence score is high enough for that character to be able to solve the puzzle in a way that is internally consistent with the game world. The problem with this approach however is that the player has a static intelligence and will become frustrated that while the solution is obvious to them, their character is too stupid to solve the puzzle, even though they ARE supposedly the character.

The third approach is to have the player view the game as a kind of benevolent puppet master, viewing the world from an objective point of view and guiding the characters through their trials and tribulations. This is what is done by pretty much every game featuring strongly characterized player characters. The player becomes immersed by relating to the characters and wanting to help them out, though they are never really seeing anything through the characters eyes. The problem with this is that the player is still disconnected from the game world which can result in the player having more desire to game the mechanics of the game and grab all the power ups rather than playing in a natural way given the context of the narrative.

The first two approaches are pretty unsuited to Junkship’s style of play and narrative, so what can we do with the third approach to help break the disconnect between the player and the character? Introduce character subjectivity to the experience! To explain what I mean by a subjective viewpoint I’ll explain a situation in terms of two viewpoints, external (objective) and internal (subjective). We’ll treat external as being a reality that’s absolute and free from personal bias, Plato’s perfect world if you will. By contrast the internal viewpoint is the world as experienced through the eyes of a character in the external reality and is very much biased and influenced by the character experiencing the external event. Games typically present the external world directly to the player, what I propose is that the internal world of the current character be what is directly presented to the character, making it easier for the player to understand the mindset of the character. This essentially means that while the events in external reality may be the same, depending on the character experiencing them the player may be given a different view that will bias thier experience in favour of the observing character.

Okay, so how can we actually do this? lets have an example, Say we have 3 characters James, Sora, and Modeki. James is arguing with Sora and Modeki is listening to them argue, this could be a pretty typical situation in Junkship and the player has the opportunity to have control over any one of the characters during this juncture. If the player was playing as James, Sora would appear to be very argumentative and disagreeable with the players dialogue tree being populated with reasonable and thought out answers, this gives the player the impression that James is right and that Sora is being a bitch (which is how James is viewing the situation). If the player was playing as Sora the roles would be reversed with James appearing to be in the wrong. If the player was playing as Modeki the (reasonably) impartial observer it would seem that both James and Sora were being petty and disagreeable.

Another situation could be where James is trying to explain the intricacies of spaceship engine design to Sora. James is knowledgeable in this area and is a natural with machines so its all obvious to him, but Sora has no idea about this stuff. As James the player would see James explaining things in a very simple and straightforward manner with Sora seemingly being unable to ‘get it’ despite how obvious it is. However as Sora, James would be talking in a very hard to understand fashion with lots of jargon thrown in to make it almost indecipherable, and it would appear that James is being unreasonable when he gets frustrated at Sora’s lack of understanding. If we extrapolate these sorts of situations out to all major plot events we can have a strictly linear narrative where the player better understands the actions of the character helping the player relate to the characters more effectively. It also gives players a chance to experience the same story in a number of different ways depending on who they are playing as, adding to replay value and the feeling of non-linearity.

Though this approach does introduce an overhead in having to write subtly different dialogue for each player character, in reality all characters could perceive most simple conversations in the same way, its only critical plot points and character building stuff that really benefits from the multiple viewpoints approach. If we wanted to we could also take the idea further to its logical extreme, to include visual and musical cues to aid in portraying the characters state of mind, e.g shifting the music to darker more sombre tones, and displaying a darker more monochromatic palette for a character that is depressed, or portraying NPC’s as shiftier, more sneaky looking characters if the player character has little trust in other people.