Archive for the ‘Procedural Landscapes’ Category

A Note on Co-ordinate Systems

November 9, 2010 4 comments

Before delving deeper into terrain construction I thought a brief note on co-ordinate systems would be worthwhile. Stellar bodies come in all shapes and sizes but as I live on planet Earth like most people basing my virtual planet upon this well known baseline makes a lot of sense.

Now the Earth isn’t quite a perfect sphere so it’s radius varies but it’s volumetric mean radius is about 6371 Km so that’s a good enough figure to go on. Most computer graphics use single precision floating point numbers for their calculations as they are generally a bit faster for the computer to work with and are universally supported by recent graphics cards, but with only 23 bits for the significand they have only seven significant digits which can be a real problem when representing data on a planetary scale.

Simply using a single precision floating point vector to represent the position of something on the surface of our Earth sized planet for example would give an effective resolution of just a couple of meters, possibly good enough for a building but hardly useful for anything smaller and definitely insufficient for moving around at speeds lower than hundreds of kilometers per hour. Trying to naively use floats for the whole pipeline and we quickly see our world jiggling and snapping around in a truly horrible manner as we navigate.

Moving to the use of double precision floating point numbers is an obvious and easy solution to this problem however as with their 52 bit significand they can easily represent positions down to millionths of a millimetre at planetary scale which is more than enough for our needs. With modern CPUs their use is no longer as prohibitively expensive as they used to be in performance terms either with some rudimentary timings showing only a 10%-15% drop in speed when switching core routines from single to double precision. Also the large amounts of RAM available now make the increased memory requirement of doubles easily justified, the problem of modern GPUs using single precision however remains as somehow we have to pipe our double resolution data from the CPU through the single precision pipe to the GPU for rendering.

My solution for this is simply to have the single precision part of the process, namely the rendering, take place in a co-ordinate space centred upon the viewpoint rather than the centre of the planet. This ensures that the available resolution is being used as effectively as possible as when the precision falls off on distance objects these are by nature very small on screen where the numerical resolution issues won’t be visible.

To make this relocation of origin possible, I store with each tile it’s centre point in world space as a double precision vector then store the vertex positions for the tile’s geometry components as single precision floats relative to this centre. Before each tile is rendered, the vector from the viewpoint to the centre of the tile in double precision space is calculated and used to generate the single precision complete tile->world->view->projection space matrix used for rendering.

In this way the single precision vertices are only ever transformed to be in the correct location relative to the viewpoint (essentially the origin for rendering) to ensure maximum precision. The end result is that I can fly from millions of miles out in space down to being inches from the surface of the terrain without any numerical precision problems.

The planet from space...

...from orbit...

...and from just a few feet off the surface

There are of course other ways to achieve this, using nested co-ordinate spaces for example but selective use of doubles on the CPU is both simple and relatively efficient in performance and memory costs so feels like the best way.

Of course numerical precision issues are not limited to the positions of vertices, another example is easily found with the texture co-ordinates used to look up into the terrain textures. On the one hand I want a nice continuous texture space across the planet to avoid seams in the texture tiling but as the texture co-ordinates are only single precision floats there simply isn’t the precision for this. Instead different texture scales have to be used at different terrain LOD levels and the results somehow blended together to avoid seams – I’m not going to go to deeply in to my solution for that here as I think it’s probably worth a post of it’s own in due course.


Osiris, the Introduction

November 5, 2010 Leave a comment

Continuing the theme of procedurally generated planets, I’ve started a new project I’ve called Osiris (the Egyptian god usually identified as the god of the Afterlife, the underworld and the dead) which is a new experiment into seeing how far I can get having code create a living breathing world.

Although my previous projects Isis and Geo were both also in this vein, I felt that they each had such significant limitations in their underlying technology that it was better to start again with something fresh.  The biggest difference between Geo and Osiris is that where the former used a completely arbitrary voxel based mesh structure for its terrain Osiris uses a more conventional essentially 2D tile based structure.  I decided to do this as I was never able to achieve a satisfactory transition effect between the level of details in the voxel mesh leaving ugly artifacts and, worse, visible cracks between mesh sections – both of which made the terrain look essentially broken.

After spending so much time on the underlying terrain mesh systems in Isis and Geo I also wanted to implement something a little more straightforward so I could turn my attention more quickly to the procedural creation of a planetary scale infrastructure – cities, roads, railways and the like along with more interesting landscape features such as rivers or icebergs.  This is an area that really interests me and is an immediately more appealing area for experimentation as it’s not an area I have attempted previously.  Although a 2D tile mesh grid system is pretty basic in the terrain representation league table, there is still a degree of complexity to representing an entire planet using any technique so even that familiar ground should remain interesting.

The first version shown here is the basic planetary sphere rendered using mesh tiles of various LOD levels.  I’ve chosen to represent the planet essentially as a distorted cube with each face represented by a 32×32 single tile at the lowest LOD level.  While the image below on the left may be suitable as a base for Borg-world, I think the one on the right is the basis I want to persue…

While mapping a cube onto a sphere produces noticeable distortion as you approach the corners of each face, by generating terrain texturing and height co-ordinates from the sphere’s surface rather than the cube’s I hope to minimise how visible this distortion is and it feels like having what is essentially a regular 2D grid to build upon will make many of the interesting challenges to come more manageable.  The generation and storage of data in particular becomes simpler when the surface of the planet can be broken up into square patches each of which provides a natural container for the data required to simulate and render that area.

At this lowest level of detail (LOD) each face of the planetary cube is represented by a single 32×32 polygon patch.  At this resolution each patch covers about 10,000 km of an Earth sized planet’s equator with each polygon within it covering about 313 km.  While that’s acceptable when viewing the planet from a reasonable distance in space as you get closer the polygon edges start to get pretty damn obvious so of course the patches have to be subdivided into higher detail representations.

I’ve chosen to do this in pretty much the simplest way possible to keep the code simple and make a nice robust association between sections of the planet’s surface and the data required to render them.  As the view nears a patch it gets recursively divided into four smaller patches each of which is 32×32 polygons in it’s own right effectively halving the size of each polygon in world space and quadrupling the polygonal density.

Here you can see four stages of the subdivision illustrated – normally of course this would be happening as the view descended towards the planet but I’ve kept the view artificially high here to illustrate the change in the geometry.  With such a basic system there is obviously a noticeably visible ‘pop’ when a tile is split into it’s four children – this could be improved by geo-morphing the vertices on the child tile from their equivalent positions on the parent tile to their actual child ones but as the texturing information is stored on the vertices there is going to be a pop as the higher frequency texturing information appears anyway .  Another option might be to render both tiles during a transition and alpha-blend between them, a system I used in the Geo project with mixed results.

LOD transitions are a classic problem in landscape systems but I don’t really want to get bogged down in that at the moment so I’m prepared to live with this popping and look at other areas.  It’s a good solid start anyway though I think and with some basic camera controls set up to let me fly down to and around my planet I reckon I’m pretty well set up for future developments.

A note on voxel cell LOD transitions

July 12, 2010 3 comments

I recently received a question from a developer who has kindly been reading my blog asking about how I tackled the joins between voxel cells of differing resolutions.  This was one of the most challenging problems raised by the voxel terrain system and so rather than put my response in a mail I thought it might be more useful to make it public for anyone else who visits.

I’ll start by saying however that after devoting time to several different strategies I never did come to a solution that I was entirely happy with – each had it’s problems some more objectionable than others but I’ll relate each experiments here…maybe someone else can take something from them and improve the results.

Before getting to my solutions, it’s probably worth first describing the problem: essentially the whole environment is made up of cube shaped cells of voxel data, each one containing geometry representing the iso-surface within that cube.  The number of sample points and therefore the iso-surface resolution within each cell is constant but  to keep the amount of data in memory and being rendered reasonable, cells close to the camera represent small areas of the world while cells further away represent proportionally larger areas.  In a manner similar to mip-mapping for textures, each level of cells is twice as large in the world as the ones  from the preceding level.  Near the camera for example a cell might cover 10 metres of world space while moving into the middle distance would switch to 20 metre cells, then 40 metre, then 80 and so on.

While a continuous representation would improve the consistency of triangle size over the view distance, the management of a cell-based approach is far simpler as individual cells can be generated, cached and retrieved very simply.  The downside however is the exactly the problem asked about – where a 10m cell abuts a 20m cell for example, every other sample point on the 10m cell will have no corresponding sample point in the 20m cell and we end up with a floating vertex that in most cases does not line up with the edge of the triangle in the 20m cell it is next to and we get a visual crack in the world geometry.

The first and method I tried was to simply displace the floating vertex along it’s normal by some distance based upon how far it was from the viewpoint.  This correlates to other simple techniques for hiding LOD cracks in 2D height fields where verts can be moved ‘up’ by some amount to hide the crack – it works to a degree in 3D too as I found and could often hide the resultant crack but unfortunately it wasn’t reliable as sometimes the normal didn’t happen to point in the best direction to hide the crack, and sometimes the nature of the voxel data itself meant that no sensible amount of movement could hide the resultant crack regardless of direction due to rapidly changing curvatures or other high frequency detail.

The second experiment was to try to create ‘fillet’ geometry that would connect the hanging vertices from the higher detail cells to the vertices in the lower detail cells.  I have used this system in the past on 2D height fields to eliminate cracks and while it’s a bit fiddly it does guarantee crack free results.  Unfortunately I had underestimated just how complex it is to extend this system from 2D to 3D – the sheer number of cases that needs to be handled to enable low detail sub-cube sides to map to higher detail sides in all possible configurations is the biggest problem, especially where a cell has a mixture of higher and lower details neighbours.

I achieved limited success with this but didn’t manage to get it working satisfactorily, eventually putting it to one side as I tried to find a less fiddly solution.

The final solution that I ended up with was to render cells that had neighbours of differing resolutions twice, calculating an alpha value in the pixel shader based upon the proximity of the point to the edge of the cell where the resolution changed.  By enabling alpha-as-coverage rendering this produced a screen space dissolve effect that while inferior to correctly connecting geometry was actually fairly visually unobtrusive in most cases – the higher frequency terrain detail fades in as you approach which hides the transition between LODs fairly well especially when combined with a degree of atmospheric fog.

It’s not perfect though and looks a little peculiar where there is high frequency detail producing large differences between LODs or when the viewpoint is moving slowly and part cross-faded features remain on screen for significant periods of time.  There is also of course a performance cost of rendering some cells twice but it’s the least evil solution I came up so I left it in.

This is one of those problems where there feels like there should be a neat solution out there somewhere but so far my internet research has not turned one up – off-line rendering solutions such as subdividing down so cells are less than one pixel across are not exactly practical!  If you do come across any improved solutions however or develop any of your own, do please post a comment or drop me a line – I would be very interested to hear about them.

Categories: Geo, Procedural Landscapes

Captain Coriolis

Continuing the theme of clouds, I’ve been looking at a few improvements to make the base cloud effect more interesting, so with the texture mapping sorted what else can we do with the clouds? Well because the texture is just a single channel intensity value at the moment we can monkey around with the intensity in the shader to modify the end result.

The first thing we can do is change the scale and threshold applied to the intensity in the pixel shader. The texture is storing the full [0, 1] range but we can choose which part of this to show to provide more or less cloud cover:

Here the left most image is showing 50% of the cloud data, the middle one just 10% and the right hand one 90%. Note that on this final image the contrast scalar has also been modified to produce a more ‘overcast’ type result. Because these values can be changed on the fly it leaves the door open to having different cloud conditions on different planets or even animating the cloud effect over time as the weather changes.

Next I thought it would be interesting to add peturbations to the cloud function itself to break up some of it’s unrealistic uniformity. First a simple simulation of the global Coriolis Effect that essentially means that the clouds in the atmosphere are subject to varying rotational forces as they move closer to or further away from the equator due to the varying tangental speeds at differing lattitudes.

The real effect is of course highly complex but with a simple bit of rotation around the Y axis based upon the radius of the planet at the point of evaluation I can give the clouds a bit of a twist to at least create the right impression:

Here the image on the left is without the Coriolis effect and the image on the right is with the Coriolis effect. The amount of rotation can be played with based on the planet to make it more or less dramatic but even at low levels the distortion in the cloud layer that it creates really helps counter-act the usual grid style regularity you usually get with noise based 3D effects.

With the mechanism in place to support the global peturbation from the Coriolis effect, I then thought it would be interesting to have a go at creating some more localised distortions to try to break up the regularity further and hopefully make the cloud layer a bit more realistic looking or at least more interesting.

The kind of distortions I was after were the swirls, eddies and flows caused by cyclical weather fronts, mainly typhoons and hurricanes of greater or lesser strength. To try to achieve this I created a number of axes in random directions from the centre of the planet each of which had a random area of influence defining how close a point had to be to it to be affected by it’s peturbation and a random strength defining how strongly affected points would be influenced.

Each point being evaluated is then tested against this set of axes (40 currently) and for each one if it’s close enough it is rotated around the axis by an amount relative to it’s distance from the axis. So points at the edge of the axis’ area of influence hardly move while points very close to the axis are rotated around it more. This I reckoned would create some interesting swirls and eddies which in fact it does:

It can produce some fairly solid looking clumps which is not great but on average I think it adds positively to the effect. (Looking at the type of distortion produced I suspect it may also be useful for creating neat swirly gas planets or stars with an appropriate colour ramp – something for the future there I hope).

So far I’ve got swirly white clouds but to make them seem a bit more varied the next thing I tried was to modulate not just the alpha of the cloud at each point but the shade as well. At first I was going to go with a second greyscale fBm channel in the cube map using different lacunarity and scales to produce a suitable result, but then I thought why not use the same channel but just take a second sample from a different point on the texture. This worked out to be a pretty decent substitute, by taking a sample from the opposite side of the cube map from the one being rendered and using this as a shade value rather than an alpha it introduces some nice billowy peturbations in the clouds that I think helps to give them an illusion of depth and generally look better:

The main benefit of re-using the single alpha channel is it leaves me all three remaining channels in my 32bit texture for storing the normal of the clouds so I can do some lighting. Now for your usual normal mapping approach you only need to store two components of the surface normal in the normal map texture as you can work out the third in the pixel shader, but doing this means you lose the sign of the re-constituted component. This isn’t a problem for usual normal mapping where the map is flat and you use the polygon normal, bi-normal and tangent to orient it appropriately, but in my case the single map is applied to a sphere so the sign of the third component is important. Fortunately having three channels free means I can simply store the normal raw and not worry about re-constituting any components – as it’s a sphere I also don’t need to worry about transforming the normal from image space to object space.

Calculating the normal to store is an interesting problem also, I tried first using standard techniques to generate it from the alphas already stored in the cube map but this understandibly produced seams along the edges of each cube face. Turns out a better way is to treat the fBm function as the 3D function it is, and use the gradient of the function at each point to calculate the normal – this is essentially the same way as the normals are calculated for the landscape geometry during the marching cubes algorithm.

With the normal calculated and stored, I then put some fairly basic lighting calculations into the pixel shader to do cosine based lighting. The first version produced very harsh results as there isn’t really any ambient light to fill in the dark side of the clouds so I changed it to use a fair degree of double sided lighting to smooth out the effect and make it a bit more subtle/believable.

Shown below is the planet without lighting, the generated normal map, the lighting component on it’s own and finally the lighting component combined with the planet rendering:

As you can see from the two right hand images there are still some problems with the system as it stands – the finite resolution of the cube map means there are obvious texel artifacts in the lighting where the normals are interpolated for a start – but I think it’s still a worthwhile addition.

Although I’m not 100% happy with the final base cloud layer effect I think that’s probably enough for now, I’m currently deciding what to do next – possibly try positioning my planet and sun at realistic astronomical distances and sizes to check that the master co-ordinate system is working. This is not visually fun but necessary for the overall project although it will probably also require some work on the camera control system to make moving between and around bodies at such distances workable.

More interestingly I might try adding some glare and lens flare to the sun rendering to make it a bit more visually pleasing – the existing disc with fade-off is pretty dull really.

Clouding the Issue

Taking a break from hills and valleys, I thought I would have a go at adding some clouds to the otherwise featureless sky around my planets. There are various methods employed by people to simulate, model and render clouds depending on their requirements, some are real-time and some are currently too slow and thus used in off-line rendering – take a look at the Links section for a couple of references to solutions I have found out on the net.

Although I would like to add support for volumetric clouds at some point (probably using lit cloud particle sprites of some sort) to get things underway I thought a single background layer of cloud would be a good starting point. Keeping to my ethos, I do of course want to generate this entirely procedurally if at all possible and as with so many other procedural effects a bit of noise is a good starting point.

In this case while I get the mapping and rendering of the cloud layer working I’ve opted to use a simple fBm function (Fractional Brownian Motion) that combines various octaves of noise at differing frequencies and amplitudes to produce quite a nice cloudy type effect. It’s not convincing on it’s own and will need some more work later but for now it will do.

Now the fBm function can be evaluated in 3D which is great but of course to render it on the geodesic sphere that makes up my atmosphere geometry I need to map it somehow into 2D texture space – I could use a full 3D texture here which would make it simple but would also consume a vast amount of texture memory most of which would be wasted on interior/exterior points so I’ve decided not to do that. I could also evaluate the fBm function directly in the shader but as I want to add more complex features to it I want to keep it offline.

The simplest way to map the surface of a sphere into 2D is to use polar co-ordinates where ‘u’ is essentially the angle ‘around’ the sphere and ‘v’ the elevation up or down. This is simple to calculate but produces a very uneven mapping of texture space as the texels are squeezed more and more towards the poles producing massive warping of the texture data.

The two images here show my basic fBm cloud texture and that same texture mapped onto the atmosphere using simple polar co-ordinates.

(ignore the errant line of pixels across the planet – this is caused by an error of some sort in the shader that I couldn’t see on inspection and I didn’t want to spend time on it if the technique was going to be replaced anyway)

The distortion caused by the polar mapping is very obvious when applied to the cloud texture with significant streaking and squashing evident eminating from the pole – obviously far from ideal.

One way to improve the situation is the apply the inverse distortion to the texture when you are generating it, in this case treating texture generation as a 3D problem rather than a 2D one by mapping each texel in the cloud texture onto where it would be on the sphere after polar mapping and evaluating the fBm function from that point. As can be seen in the images below this produces a cloud texture that gets progressively more warped towards the regions that will ultimately be mapped to the poles so it looks wrong when viewed in 2D as a bitmap, but should produce better results when mapped onto the sphere:

As you can see in the planetary image, the streaking and warping is much reduced using this technique and the cloud effect is almost usable but if you look closely you will see that there is still an artifact around the pole albeit a much smaller one – it would be significantly larger when viewed from the planet’s surface however so is still not acceptable. One way to ‘cheat’ around this problem is to simply ensure that cloud cover at the pole is always 100% cloud or 100% clear sky to hide the artifact and some released space based games that don’t require you to get very close to the planets do this very effectively, but in a world of infinite planets it’s a big restriction that I don’t want to have to live with.

Another downside of polar mapping is that the non-uniform nature of the texel distribution means that many of the texels on the cloud texture aren’t really contributing anything to the image depending on how close to the pole they are which is a waste of valuable texture memory.

So if polar mapping is out what are we left with? Well next I thought it was time to drop it altogether and move on to cubic mapping, a technique usually employed for reflection/environment mapping or directional ambient illumination. With this technique we generate not one cloud texture but six each representing one side of a virtual cube centred around our planet. With this setup when shading a pixel the normal of the atmospheric sphere is intersected with the cube and the texel from that point used. The benefit of cube mapping is that there is no discontinuity around the poles so it should be possible to get a pretty even mapping of texels all around the planet, making better use of texture storage and providing a more uniform texel density on screen amongst other things.

So ubiquitous is cube mapping that graphics hardware even provides a texture sampler type especially for this so we don’t even need to do any fancy calculations in the pixel shader, we simply sample the texture using the normal directly which is great for efficiency. The only downside is that now we are storing six textures instead of one the memory use does go up, so I’ve dropped the texture size from 1024×1024 to 512×512 but as each texture is only mapped onto 1/6th of the surface of the sphere the overally texel density actually increases and the more effective use of texels means the 50% increase in memory usage is worthwhile.

The two images below show how one face of the texture cube and the planet now looks with this texture cube applied:

Again it’s different but the edges of the cube are pretty clear and ruin the whole effect, so as a final adjustment we again need to apply the inverse of the distortion effect implied by moving from a cube to a sphere and map the co-ordinates of the points on our texture cube onto the sphere prior to evaluating fBm:

Finally we have a nice smooth and continuous mapping of the cloud texture over our sphere. Result! To show how effective even a simple cloud effect like this can be in adding interest to a scene here is a view from the planet surface with and without the clouds:

There is obviously more to do but I reckon it’s a decent start.

Mountains and Ridges

I’ve been looking at different ways to generate terrain recently with a focus on trying to make something that’s a bit more realistic. One of the main problems with Geo’s terrain so far is the same problem that most of my previous experiments have suffered from and the same problem you will see on the majority of procedural landscape demos out there – the landscape is too homogenous, it’s too ‘samey’.

This is usually a result of whatever fractal or noise based function that is used to generate the heights being applied in too uniform a fashion over the whole landscape area, it’s also a result of the fact that most of these functions treat 3D space as a uniform entity so there is no sense of direction and no knowledge of the processes of fault formation and erosion that shape real landscapes.

The image here taken from Geo shows clearly what I mean – a fairly constant lumpiness that isn’t exactly convincing:

Now matters can be improved somewhat by using more noise functions at lower frequencies to control the parameters but you still end up with no directionality and something that while less regular is still far from realistic. This second image is taken from Google Earth and shows the sort of ridges and valleys that I am after but so far lacking:

There are several research papers out there I’ve found so far that present various techniques for producing more physically accurate simulations of terrain based upon studies of real geological formations, wind and water erosion and other climactic factors, but these are invariably very complex, very slow or only model a certain effect in isolation – I really want to develop something that runs while not in real time at least in seconds or minutes rather than hours and I need to understand it completely so I can alter and tweak it to get the effect I want.

Not being a mathematical genius I find many research papers quite impenetrable but what most annoys me is when they are deliberately so – simple coding concepts expressed in complex algebraic formulas for example when half a dozen lines of pseudo-code would make it blindingly obvious to anyone with even rudimentary coding ability. I’m not anti-academia, and I’m certainly not anti-research; I just want people to express their ideas in a form that will *help* others understand and develop them rather than in a form that is apparently designed just to make them look as clever as possible.

Okay, with that personal rant over – being unwilling to get into the complexities of real geological simulation what I thought I would do therefore is have a bit of a go at trying to create something that was closer to real world mountains and valleys but was still controllable with just a couple of parameters. It also had to be quite efficient to generate and combine well with other procedural techniques I may employ.

The plan I came up with was to try to ‘grow’ a set of line segments representing the mountain ridges I wanted then calculate the height of the terrain as a function of the distance of each point from one of these ridges. The ridge line segments are 2D and so can be easily visualized by rendering them to a bitmap but are mapped onto the surface of the planet using a simple transformation.

Shown here is one of the first implementations of this system, it starts with a single point located roughly at the centre from which three ridges head out in randomly chosen directions – although the directions are chosen to not be too close to each other. Each ridge is formed from a number of consecutive segments with a random orientation change applied before each one is added making the ridge meander around in a more convincing fashion. The segments also get progressively lower in altitude and there is a random chance at each step that the ridge will fork into two with each child ridge heading off in a random direction based off the direction of the original.

From this I then had a look at working out height values based on the distance of each point from the closest ridge, the results are shown here both as a grayscale of the height field and as it appears when applied to a planet surface

It was quite an encouraging result and made me feel I was on the right path at least to produce the kind of effect I wanted, but there was obviously much more to be done. The first improvement was to do something about the function that works out the height of a terrain point from it’s distance to the nearest ridge line segment. The image above was generated using a fixed linear distance function but this doesn’t make much sense really as the ‘tail’ end of the segments are much lower in altitude than the roots and so should have a lower influence. Taking this into account by scaling the distance over which a segment has an influence based upon it’s height gives a better result:

Now a single mountain does not a range make, so next I tried generating ridges from multiple points combining the results by taking the highest point at each intersection:

Which looks a bit better, and while as many points as required could be combined in this way, I thought it might be nice to be able to generate ridge line segments all starting off from a connected ‘master ridge’ rather than discrete points. This master ridge formation is controlled by specifying a number of spawn points just like for the images above, but this time rather than treating them independently, the program creates a sequence of connected segments directly between the spawn points:

It’s pretty uninteresting with straight lines between the points, but we can make it more interesting by subdividing these connecting segments into smaller pieces and displacing the newly created intermediate points by some sort of random function. The method I chose is very simple and something of a fractal classic:

• take each straight segment shown above and split it at it’s middle point into two
• displace the newly created middle point by a random distance in a direction perpendicular to the original line
• repeat this process recursively on the two new half-length segments as long as they are longer than some minimum threshold.

What we now get is something a lot more interesting and closer to what we might expect from a mountain ridge line:

Of course we don’t want just one big ridge, so by adding in the spawning of child ridges from the sides of our master ridge we get something a bit more like what we were after at the beginning, a combination of ridges in various directions and sizes but all heading down from our master ridge. These child ridges are set to spawn randomly along the length of the master ridge but head out in a direction roughly perpendicular to the direction of travel of the master ridge at their spawn point so they generally fan out from ridge in a fairly sensible pattern:

Looking at this effect now I reckon it would be even better to spawn some additional children from the end points of the master ridge to get rid of the ‘bulb’ of height influence around those points…something to try I think.

One thing obvious from these images however is the way the land on either side of the ridges slopes away at a constant slope producing a hard edge along the ridge itself and an unrealistically constant gradient on either side. To solve this my next step was to exchange the linear distance function used up to this point for a hermite interpolation that provides a smoother blend between the points at the ridge top and those at the bottom of the slope. The difference can be clearly seen on these two simple graphs:

You can see the smooth-step graph on the right hand side forms a far more natural shape for the hillsides and because the slope becomes more gradual towards the top (the right hand edge of the graph) the ridge line itself is wider, smoother and far less like a knife edge.

Finally to make things a bit more interesting again let’s add some higher frequency perturbations using a ridged fractal similar to that from our original homogenous landscape but at a much lower amplitude just to add variety over our too-smooth slopes:

This is finally starting to look a bit more like some mountains although there is fairly obviously still a very long way to go to achieve something that really does look realistic – there are some undesirable artifacts where ridge influences meet for example producing fairly artificial looking gulleys, but it’s certainly promising enough I think to continue the experiment.

PS: Hope you found this interesting, it certainly helps me get my head around the process documenting it in this much detail – constructive feedback and comments are as always welcomed!

Planetary Basics

May 20, 2010 1 comment

I thought maybe a bit of a description of how Geo represents it’s planetary bodies might be interesting, it will nail it down in black and white for me if no one else anyhow.

As procedural landscapes have been an interest of mine for many years it’s no surprise that I’ve played about with many little projects over those years looking into different techniques and algorithms. All of these earlier projects however suffered from the same limitation that is prevalent in many of even the latest games today – they represented their landscapes as simple two-dimensional grids of altitude values known usually as height fields.

Now height fields are pretty much ubiquitous with landscape rendering because they are simple, contain a very high degree of coherency and thus lend themselves to a variety of high speed rendering and collision algorithms that take advantage of those facts.
Height fields however do by their nature however suffer from the problem of being two dimensional with each point on the landscape represented only by a height value. This precludes any form of vertical surface on the landscape such as a cliff face along with concave constructs such as overhangs and caves, lending height field based landscapes a distinctive simplicity.

There have been various extensions applied to basic height fields to work around these limitations at least in part, games such as Crysis use selective areas of voxel based geometry to produce overhangs for example and many games employ sections of pre-built geometry such as cave or tunnel entrances that can be placed in the world to hide the join picture-frame style between the height field landscape geometry and the non-height field based interiors.

Rather than try extending something I have played about with previously however I thought it would be more interesting to try something completely new, so with Geo I’ve chosen to represent entire planet as single voxel spaces from which geometry is generated. These voxels are represented using a fairly standard octree structure so they can be rendered at differing levels of detail as required – see Wikimedia amongst others for more information on Octrees and Voxels

A simulated Earth for example starts with a single voxel containing the entire planet which is rendered using geometry generated with the marching cubes algorithm over a 16×16×16 grid. The values fed in to the marching cubes come from a planetary density function which essentially evaluates for a given point in space how far it is from the surface of the planet; +ve being above the planet surface and –ve being below. When the marching cubes process these density values the iso-surface produced at the zero density value then gives the geometry for the surface of the planet – probably a couple of thousand triangles for this lowest LOD level.

As we get closer to the planet the voxel is split into eight children at the next level down in the octree and geometry generated for each of them for rendering and so on. What happens first of course is the viewpoint position is used to determine which voxels from which levels of the octree should be rendered – voxels close to the viewpoint are taken from deeper in the octree and so produce higher fidelity geometry while those further from the viewpoint use voxels from lower in the tree and thus produce lower fidelity geometry. A natural level of detail scheme thus falls out of the tree traversal ensuring as uniform a triangle density as possible is produced on screen.

Other optimizations such as culling voxel bounding boxes against the view frustum helps reduce the amount of geometry rendered and an asynchronous geometry generation system is employed so rendering is not slowed down while the CPU generates geometry from the density field – voxel geometry simple appears as it’s generated in a closest-first type fashion and cached in memory for future frames. There is plenty of scope for more advanced visibility culling techniques such as hierarchical Z buffer tests but this will do for now.

While initial experiments are based around basically Earth like planets, the real power of this approach is that it can represent any form of geometry at all, so half-destroyed blown apart planet husks are entirely possible along with sprawling cave systems, vertical cliff faces and even gravity defying floating rock precipices – there should really be no limit.

Anyway, that covers the basics and is probably enough for now – take a look at the screenshots to see how it’s coming along but bear in mind please that it is still very early days so apart from the major feature omissions such as atmospheric scattering, vegetation, water and infrastructure there are also many major glitches with the code that still need ironing out.

– John