3/31/2015 PA199 Advanced Game Design Lecture 7 Terrain Generation Dr. Fotis Liarokapis 31st March 2015 Terrain Data • Terrain data relates to the 3D configuration of the surface of the Earth • Map data refers to data located on the surface of the Earth (2D) • The geometry of a terrain is modeled as a 2 ^-dimensional surface Terrain Models • Global terrain model - Defined by a single function interpolating all data • Local terrain models - Defined on a partition of the domain into patches • They represent the terrain by means of a different function on each of the regions in which the domain is subdivided • In general it is very difficult to find a single function that interpolates all available data - Usually local models are used Mathematical Terrain Models V A topographic surface or terrain can be mathematically modeled by the image of a real bivariate function: z = rj> (x, y) Defined over a domain D such that D c5R2 The pair T=(D, rj>) is called a mathematical terrain model Unidimensional profile of a mathematical terrain model Digital Terrain Models Video l 3/31/2015 Digital Elevation Models (DEMs) DEM Video DEM is set of regularly or irregularly spaced height values -Terrain elevation data No other information Elevation Data Acquisition • Elevation data can be acquired through: - Sampling technologies • i.e. on-site measurements or remote sensing techniques - Digitisation of existing contour maps • Elevation data can be scattered (irregularly distributed) or form a regular grid • The set of non-crossing lines can form a collection of polygonal chains UK DEM Data Sources • OrdnanCe SUrVey: http://www.ordnancesurvev.co.uk/ -Landform Panorama • Source scale: 1:50,000 • Resolution: 50m • Vertical accuracy: ±3m -Landform Profile • Source scale: 1:10,000 • Resolution: 10m • Vertical accuracy: ±0.3m Landform Panorama Landform Profile Light Detection And Ranging (LIDAR) • LIDAR is a remote sensing technology that measures distance by illuminating a target with a laser and analyzing the reflected light -Uses ultraviolet, visible or near infrared light to image objects -Can target a wide range of materials • i.e. non-metallic objects, rocks, rain, chemical compounds, aerosols, clouds, single molecules 2 3/31/2015 Digital Terrain Models (DTMs) DTM Examples Digital terrain models represent an approximation of mathematical terrain models In general, a larger number of sampled points allows for a better representation: multiresolution terrain models Sampled model Digital terrain model 3 3/31/2015 DTM Types Polyhedral Terrain Models (PTM) Polyhedral terrain models Gridded elevation models Contour maps A PTM for a set of sampled points V can be defined on the basis of: - A partition of the domain D into polygonal regions having their vertices at points in V - A function f that is linear over each region of the partition • The image of f over each polygonal region is a planar patch to guarantee continuity of the surface along the common edges PTM Properties • They can be used for any type of sampled pointset - Regularly and irregularly distributed • They can adapt to the irregularity of terrains • They represent continuous surfaces Triangulated Irregular Networks (TINs) • TINs are the most commonly used PTMs -Each polygon of the domain partition is a triangle TINs Example V TINs for Regular Data Regular sampling is enough in areas where the terrain elevation is more or less constant Example of a TIN based on irregularly distributed data 4 3/31/2015 TINs Properties TIN Video They guarantee the existence of a planar patch for each region (triangle) of the domain subdivision (three points define a plane) -The resulting surface interpolates all elevation data The most commonly used triangulations are Delaunay triangulations Why Delaunay Triangulations They generate the most equiangular triangles in the domain subdivision -Thus minimising numerical problems • e.g. Point location Their Dual is a Voronoi diagram Therefore, some proximity queries can be solved efficiently Why Delaunay Triangulations It has been proven that they generate the best surface approximation independently of the z values - In terms of roughness Several efficient algorithms to calculate them exist! Delaunay Triangulations V Voronoi Diagrams Intuitively: given a set V of points, among all the triangulations that can be generated with the points of V, the Delaunay triangulation is the one in which triangles are as much equiangular as possible - Delaunay triangulations tend to avoid long and thin triangles Does P lie inside t or on its boundary? Given a set V of points in the plane, the Voronoi Diagram for V is the partition of the plane into polygons such that each polygon contains one point p of V and is composed of all points in the plane that are closer to p than to any other point of V 5 3/31/2015 Voronoi Diagrams Voronoi Diagrams Example Property -The straight-line dual of the Voronoi diagram of V is a Delaunay triangulation of V Dual -Obtained by replacing each polygon with a point and each point with a polygon Connect all pairs of points contained in Voronoi cells that share an edge Voronoi Diagrams Example Voronoi Diagrams Usage Used as underlying structures to solve proximity problems: - Nearest neighbor (what is the point of V nearest to P?) - K-nearest neighbors (what are the k points of V nearest to P?) Gridded Elevation Models • A Gridded Elevation Model is defined on the basis of a domain partition into regular polygons Regular Square Grids (RSGs) • The most commonly used gridded elevation models are Regular Square Grids (RSGs) where each polygon in the domain partition is a square • The function defined on each square can be a bilinear function interpolating all four elevation points corresponding to the vertices of the square 6 3/31/2015 RSG Example RSG Stepped Model Alternatively, a constant function can be associated with each square (i.e., a constant elevation value) This is called a stepped model - It presents discontinuity steps along the edges of the squares Unidimensional profile of a stepped mode TINsvs RSGs Both models support automated terrain analysis operations -RSGs are based on regular data distribution -TINs can be based both on regular and irregular data distribution Irregular data distribution allows to adapt to the "variability" of the terrain relief -More appropriate and flexible representation of the topographic surface Digital Contours • Given a sequence {vO,vn } of real values, a digital contour map of a mathematical terrain model (D, t\>) is an approximation of the set of contour lines • {(x,y) e D, cfj(x,y) = vi} i = 0, n Plane z = v Digital Contour Maps V Digital Contour Maps Contours are usually available as sequences of points A line interporlating points of a contour can be obtained in different ways Typical examples -Polygonal chains - Lines described by higher order equations 3/31/2015 Digital Contour Maps Properties They are easily drawn on paper They are very intuitive for humans They are not good for complex automated terrain analysis Problems with DEMs Issues worth considering when creating/using DTMs -Quality of data used to generate DEM -Interpolation technique -Give rise to errors in surface such as: -Sloping lakes and rivers flowing uphill -Local minima -Stepped appearance -etc Example Applications Visualisation -Terrain and other 3D surfaces Visibility analysis -Intervisibility matrices and viewsheds Hydrological modelling -Catchment modelling and flow models Engineering -Cut & fill, profiles, etc V Terrain Visualisation Analytical hillshading Orthographic views - Any azimuth, altitude, view distance/point - Surface drapes (point, line and area data) Animated 'fly-through' What if? modelling - Photorealism - Photomontage -CAD 8 3/31/2015 Hillshading Video Fractal Terrain Generation Terrain Map Height Map: z = f(x, y) - x and y are sampled on a 2D integer grid Real data - Satellite, Elevation maps (previous lecture) Synthetic -Texture map, Noise functions B^^H Terrain Map Connect samples into a mesh 0.0-i-1-1.0 Fake Terrain V Random Terrain Generate the height-field Random process - This can be control led Reflects "realistic" terrain in some way Simple: - Terrain(x,y) = rand( MAX_HEIGHT ) - Results in random noise Next step: - Smooth the terrain generated above - Finite Impulse Response (FIR) filter: 1 1 1 1 1 1 1 1 9 3/31/2015 Procedural Modeling With Fractals Procedural Modeling -Compute geometry "on-the-fly" Fractals -Model Natural Phenomena - Self Similarity • Mountains, fire, clouds, etc, -Scales to infinity • Add or "make up" natural looking details with mathematical tools Fractals - A Definition A geometrically complex object, the complexity of which arises through the repetition of some shape over a range of scales - Sufficient definition for describing terrains A hybrid multifractal made from Worley's Voronoi distance basis Fractals in Nature Fractal Geometry • Fractals are common in: -Mountains, clouds, trees, turbulence, circulatory systems in plants and animals • Wide variety of other phenomena such as: -Noise in transistors -Fluctuations in river fluxes Fractal geometry is very powerful! - But not sufficient for describing the complex forms found in Nature Mathematics are simple -Based on the Euclidean geometry of lines, planes, spheres and cones Fractal geometry has very little use in describing man-made objects 10 3/31/2015 Fractal Dimension • Euclidean dimensions - l, 2, 3, 4,... • Fractal - 1.2342, 2.7656 • Measure of detail or roughness of a fractal -D = (lnN)/(lnl/s) Brownian Motion • One of the most realistic ways of representing natural objects is the Brownian motion method because of the ability of creating peculiar curves • Brownian method has been used to describe the chaotic and random manner in which a particle moves in a fluid -Application in terrains Graph of a Brownian Sample Function A simulation of a Brownian Path in 2-Dimensions Fractional Brownian motion (fBm) • fBm consists of steps in a random direction and with a step-length that has some characteristic value -Also known as the Random Walk Process - Hence the random walk process • A key feature to fBm is that if you zoom in on any part of the function you will produce a similar random walk in the zoomed in part Differences • The main difference between fBm and regular Brownian motion is that while the increments in Brownian Motion are independent they are dependent in fBm -This dependence means that if there is an increasing pattern in the previous steps, then it is likely that the current step will be increasing as well Code Example of fBm total = O.Of; //for each pixel, get the value frequency = 1.0f/(float)hgrid; amplitude = gain; for (i = 0; i < octaves; ++i) { total += noise((float)x * frequency, (float)y*frequency) * amplitude; frequency *= lacunarity; amplitude *= gain; } map[x][y]=total; //now that we have the value, put it in 11 3/31/2015 Terrain using fBm Noise Midpoint Displacement ID A simple approach is to generate a heightmap using fBm noise - Results look ok but not very realistic • Since fBm is homogeneous and isotropic Type of polygon subdivision algorithm, also a fractal function Created to simulate tectonic uplift of mountain ranges One of its main input parameters is the roughness constant r Midpoint Displacement ID Midpoint Displacement ID Step 0 Displace the midpoint of the line by some random value between (-d, d) Step 3 Keep iterating until you get the required detail Always remembering to reduce d After every step Step 1 Step 2 Now reduce the range of your random function " depending on r by d* = pow( 2 , -r) Again displace the midpoint of all the line segments and reduce your Random function's range Nth step How does r affect the outcome? If r = 1 Your d will half each iteration If r > 1 d increases faster generates smooth terrain If < 1 d increases slowly generates chaotic terrain Diamond - Square Algorithm V Diamond - Square Algorithm Example Also called the cloud fractal, plasma fractal or random midpoint displacement The 2D version of the original Midpoint displacement algorithm - Therefore it also has a roughness constant The algorithm works best if it is run on square grids of width 2"n - This ensures that the rectangle size will have an integer value at each iteration 12 3/31/2015 ^^Diamond - Square Algorithm Methodology Algorithm starts with a 2 x 2 grid The heights at the corners can be set to either: - Zero, a random value or some predefined value iamond - Square Algorithm Methodology. The first step involves calculating the midpoint of the grid based on its corners and then adding the maximum displacement for the current iteration - Called the Diamond step Because if you render this terrain you will see four diamond shapes E=(A+B+C+D)/4 + Rand(d) Rand(d) can generate random values between -d and +d 9 V First Step: Diamond Step The first step involves: - Calculating the midpoint of the grid based on its corners and then - Adding the maximum displacement for the current iteration E = (A+B+OD)/4 + Rand(d) Rand(d) can generate random values between -d and +d Second Step: Square Step V Calculate the midpoints of the edges between the corners Since the first iteration is complete, now d is reduced by: - d *= pow(2, -r) • where r is the roughness wrapping G = (A+B+E*E)/4 + rand(d) H = (B+D+E+E)/4 + rand(d) I = (D+C+E+E)/4 + rand(d) F = (A+C+E+EJ/4 + rand(d) Non-wrapping G = (A+B+E)/3 +rand(d) same for H.I.F Third Step: Second Iteration Start the second iteration Again perform the diamond step J = (A+G+F+E)/4 + rand(d) K = (G+B+E+HJ/4 + rand(d) L=(F+E+D+l)/4 + rand(d) M = (E+H+l+C)/4 + rand(d) Remember this d is smaller than the one in the first iteration Fourth Step: Square Step ® Do the square step and continue subdividing -Until you reach the desired level of detail wrapping O = (A+G+J+J)/4 + rand(d) P = (J+G+K+EJ/4 + rand(d) Q = (J+E+L+F)/4 + rand(d) N = (A+F+J+J)/4 +rand(d) Non-wrapping O = (A+G*J)/3 + rand(d) N= (A+F*J)/3 + rand(d) 13 3/31/2015 Diamond - Square Algorithm Summary • While length of square sides > 0 - Pass through the whole array and apply the diamond step for each square - Pass through the whole array and apply the square step for each diamond - Reduce the range of the random displacement Smoothness of Terrain Lorentz and Gaussian distributions for the height array can control the smoothness of the terrain height = y = (tandomnumbet) x--—^ ^ - (x-x„) +(z-z„) +D2/8 — where (x0, z0) is the position of the peak and D2 is the length of the square The value of the width affects the smoothness of the terrain — By decreasing the width of the bell-shaped distribution the terrain becomes steeper Outer Boundaries Loop the Old Terrain Three solutions can be considered: -Large terrain • The user would never reach the outer boundary -Loop the old terrain • When the user reaches a boundary the user reenters the map on the opposite side -Infinite terrain • When the user reaches a boundary an extension to the map is added 14 3/31/2015 Other Techniques Cracked Terrains Cracked terrains for dry lakes and riverbeds Throw random points onto the plane Construct the Voronoi diagram and use the graph to etch into the terrain Multifractals Multifractal Code Example A better choice would be to use Multifractals - Proposed by Kenton Musgrave These are fractals whose dimension/roughness varies with location * Procedural raul tlfractal evaluated at 'point." * Parameters: * "H" determines tne highest fractal dlmensior * "lacunarity" Is gap between successive frequencies * "octaves" is the number of frequencies in the fBm * "offset" is the aero offset, which determines multifractality for Hit i-0; Koctaves; if+> 1 value *- Choi set point > + offset! * pow< la' point *- lacunarity: Other Multifractals V Hybrid multifractals -Called hybrid because they are both additive and multiplicative multifractals Ridged multifractals -Similar to Perlin's turbulence noise -They calculate l-abs(noise) so that the resulting "canyons" from abs(noise) become high ridges Other Multifractal Examples Ridged multifractal terrains : taken from Texturing and Modeling: A Procedural Approach pg 518 (left) pg 480{right) 15 3/31/2015 More Controls • To create plateaus, add a min function to flatten out high areas More Controls.. • Multiply by a Guassian filter to limit the mountain range More Controls. • To create a plain, add a max function to flatten out low areas More Controls... • To create valleys, create a lower amplitude and rather smooth terrain to use as the max operator — M 16 3/31/2015 Ridges • Quantize a terrain to create ridges - Use directly or as the min function -Can also be done as a transfer function that maps f(x)->g(x) Fault Line Algorithm • This algorithm is a very simple one, yet its results, although not the best, are pretty good • The technique is not limited to planar height fields, being also applicable to spheres to generate artificial planets -Can also approximate real world terrain features such as escarpments, mesas, and seaside cliffs Fault Line Algorithm Fault Line Algorithm Start with a planar height field - All points have zero height Then select a random line which divides the terrain in two parts - The points to one side of the line will have their height displaced upwards - The points on the other side will have their heights displaced downwa rds The red points will have their height decreased, whereas the blue points will have their height increased - So the terrain has two distinct heights If we keep dividing the terrain can get something that has valleys, mountains and so on First step in faulting process 1 iteration 100 iterations 400 iterations ^?5nerating Fault Lines in a Height Field v Grid • Randomly pick two grid points p± and p2 • Calculate the line between them • Go through all the points in the height field and add or subtract an offset value depending on what side of the line they are located • Before the next fault is drawn reduce the range of the offset by some amount dist = 0 I-«, dist c 0__ 17 3/31/2015 Filtering Height Fields Variations to the Fault Line Algorithm Height fields generated by this algorithm need to be filtered to look more realistic -A low pass filter can be used Particle Deposition Simulates volcanic mountain ranges and island systems - Drop random particles in a blank grid -Determine if the particle's neighboring cells are of a lower height • If true, increment the height of the lowest cell • Keep checking its surrounding cells for a set number of steps or until it is the lowest height among its surrounding cells • If not, increment the height of the current cell Particle Deposition E V Generated after 5 series of 1000 iterations Perlin Noise V Terrain Coloring Using a sampling of 2D Perlin Noise provides smooth hills Using a ID texture map based on the altitude can provide many useful mapping 18 3/31/2015 Terrain Coloring Striped ID texture map Terrain Coloring Using a 2D texture map provides richer detail, but is independent of the terrain Terrain Coloring... More advanced coloring is based on altitude and slope Eft's Rolling Hills Scaling in one dimension gives smooth rolling hills Height Fields Issues They cannot generate overhangs or caves Height Fields Potential Solutions • "Mushrooming" effects that involve the manipulation of vertex normals -To render height field textures with overhangs • The game Halo Wars implemented a new type of height field called a vector height field -Stored a vector to displace a vertex instead of a height value 19 3/31/2015 Realistic Terrain Video 2 Erosion Hydraulic Erosion -Water (rain) depositing to settle in height field Thermal Weathering -"Any material that knocks material loose, which then falls down to pile up at the bottom of an incline." 20 3/31/2015 Hydraulic Erosion Hydraulic erosion refers to the natural process in which the motion of fluids, specifically water, produces mechanical weathering over the soil * (Globe Tourism 2014| Cairdshill Quarry (Burgess 2009| Erosion Examples - Erosion by Wind and Water References • https://www.goog! e.co.uk/#q=ordnance+survev • http://ned.usgs.gov/ • http://en.wikipedia.org/wiki/Digital elevation model • http://wiki.gis.com/wiki/index.php/Contour line • http://wiki.gis.com/wiki/index.php/Digital Elevation Model • http://www.gdcvault.com/plav/1277/HALO-WARS-The-Terrain-of • http://davis.wpi.edu/~matt/courses/fractals/brownian.html • http://code.google.eom/p/fractalterraingeneration/wiki/Fractional Brownian Motion • http://www8.cs.umu.se/kurser/TDBD12/HT01/papers/MusgraveTerrain00.pdf • http://www.lighthouse3d.com/opengl/terrain/index.php37fault • http://www.decarpentier.nl/downloads/lnteractivelvSvnthesizingAndEditingVirtualOu tDoorTerrain report.pdf • http://www.gameprogrammer.eom/fractal.html#midpoint • Musgrave, et al. "The Synthesis and Rendering of Eroded Fractal Terrains", Siggraph 1989 • Ebert, David S., Musgrave, F. Kenton, Peachey, Darwyn, Perlin, Ken and Worley, Steve Texturing and Modeling: A Procedural Approach, 3rd edition. USA. Morgan Kaufman Publishers, 2003 Bibliography • DeLoura, Mark. Game Programming Gems. Charles River Media, 2002. • Martz, Paul. "Generating Random Fractal Terrain." Game Programmer. Publisher Robert C. Questions 21