Views
3 years ago

DNDJ 3-6 June.indd - sys-con.com's archive of magazines - SYS ...

DNDJ 3-6 June.indd - sys-con.com's archive of magazines - SYS ...

The Science Behind the

The Science Behind the ArtExploring Fractal Landscapes with GDI+Generate realistic landscapes with hills, valleys, and coastlines,and investigate the features of GDI+BY KIERANMULCHRONEfractal images are strikinglybeautiful, bright, and complexand they’re everywherethese days – from art galleriesto image compression to moviegraphics to environmental modelling(see Figure 1). It really is amazing tosee a concept from the dusty world ofmathematics jump up and grab theworld’s attention. Fractals and associatedconcepts came into being justat the time that powerful computersbecame cheap and widely accessible,and this is no coincidence. In the pastit was widely assumed that complexphenomena such as coastlines, trees,and mountain shapes could only bedescribed by complex and difficultmathematics, which could only beunderstood by a select few.This view has now been turned onits head and we can use simple equationsto generate immense complexityjust like that seen in nature. We cangenerate this complexity by using acomputer to churn through millionsof simple computations, hence therelationship between the emergencesof fractals and computing. The reasonI like fractals so much is that, togetherwith chaos theory and nonlineardynamics, they have brought mathematicsinto the “cool science” domain.Another reason I like fractals is thatalthough they look complex, they aresimple to generate (well, simple fora computer!). When equipped witha computer and some programmingskills, this new branch of mathematicsis virgin territory that can be exploredin an experimental and visual manner.I find that to be an exciting prospect.In this article I will show youhow simple it is to generate imagesof fractal landscapes complete withcoastlines, sea, and relief shading,just like those illustrated in Figure 1.Fortunately the GDI+ library of the.NET framework makes it equallysimple to render these images in planview as bitmaps. Ideally these shouldbe presented in 3D but that wouldintroduce another level of complexitythat is beyond the scope of the currentarticle.4Generating Fractal LandscapesMaking Random NumbersFirst of all the .NET framework providesa Random class specifically forgenerating random numbers; however,for the current example we require thenumbers to be distributed accordingto the normal (hopefully familiar bellcurve) distribution, whereas Randomf1Figure 1: A sequence of fractallandscapes generated usingthe computational and graphicscapabilities of .NET and GDI+.Each image is made by zoomingin on a small part of the previousimagegives us uniform or evenly distributedrandom numbers (i.e., each numberis equally likely to occur). In a normaldistribution numbers near a specifiedaverage occur more often than numbersaway from the average. A normaldistribution is characterised by a mean(i.e., average) and a variance, whichdescribes how far away from the meanvalues may occur (see Figure 2).For example, a large variance resultsin data spread widely around the average,whereas a small variance gives datatightly clustered around the average. Inorder to implement normally distributedrandom numbers in code I have createda new class called normal, whichis derived from the .NET Random class,as this saves a whole lot of work. It hastwo private data members for meanand variance implemented as properties,which can be specified in theconstructor. The base class constructorof Random is called and its Randomnumber generator is seeded using thecurrent date and time. Finally I haveadded a method called NextNormal,which gives normally distributedRandom numbers by slightly modifyingRandom’s NextDouble method.4Random DisplacementsMuch of the algorithm for generatinga fractal landscape involvesmaking random adjusts to the heightof points on a square grid. If therandom displacements were alwaysof the same order of magnitude thenas square grid became smaller andsmaller, the displacements wouldbecome large in comparison tothe individual squares and leadingto a very jagged and unrealisticlandscape. We counteract this byscaling the random displacementsaccording to size of the smallestsquare. Of course we could try anystrategy we like to achieve this and indoing so many weird and wonderfullandscapes can be generated. Theusual approach however is to generaterandom displacements from a10June 2005 • dotnetdevelopersjournal.com

f 2f 3Figure 2: Illustrates three instancesof the normal distribution all withaverage 0. The variance is 1 forthe tallest curve and then takes thevalues 2 and 3 for the progressivelylower curves. Higher variance hasthe effect of making values locatedaway from the average more likelyto occur.Figure 3: Schematic illustration ofthe landscape-generating algorithm.Given the elevation of points on asquare grid (i.e., the grey points in(a)) the elevations of points on afiner grid can be calculated (bothblack and grey points in (c)). First,the elevation of the midpoint ofeach square is the average of thefour diagonally adjacent grey points(see (b)) plus some random displacement.Next the elevation ofthe remaining points (i.e., the blackpoints in (c)) is calculated as theaverage of the four laterally adjacentpoints.normal distribution with a mean of0 and a variance of (2h 2 ) α where h isthe side length of the square and α isa value between 0 and 1. Therefore,as h gets smaller the variance getssmaller giving proportioned randomdisplacements. The α parameteradditionally allows us to control thejaggedness of the landscape closerto 0 means jagged and closer to 1means smoother. The fractal dimension(D) of the landscape is calculatedfrom α as D = 3 – α.4Landscape AlgorithmThe algorithm is relatively simpleand consists of taking a large squareand filling in the details by progressivelyquartering the square andadjusting heights randomly.I have decided to take an approachthat makes the coding less taxing andmore efficient. Usually we would haveto deal with three space coordinates(x,y,z), however if we use a squarearray of floats to represent the landscapethen, by choosing a suitablesize, the indices of the array can correspondto the (x,y) coordinates andthe value stored at each array locationrepresents the height (z). For example,suppose that I sized my array to be 9by 9 (= 2 3 + 1), then I can continuouslyhalf my array to get integer indices i.e.,half of (0,8) is 4, half of (0, 4) is 2, halfof (4, 8) is 6, etc. Therefore choosingmy array to be of size [2 n + 1, 2 n + 1]where n is a positive whole numbermakes halving squares painless.For simplicity I have chosen n= 9, so my array is 513 by 513 andultimately a bitmap of size 512 by512 will be generated. A variablecalled level is used to orchestratethe level of detail which needs to beinserted at any given stage and cantake values between 1 and n (i.e. 9right now). Using the level I can calculatethat the current square is oflength 2 n /2 level-1 and that the quarteredsquare is of length 2 n /2 level .For example, at level 1 the currentsquare is of length 512 and thequartered square is of length 256.To begin with I set the level to1 and give values to the vertices ofthe current square (0,0), (0,512),(512,512), (512,0) of 0 plus a randomdisplacement with variance (2h 2 ) αwhere h is 2 n /2 level-1 , the currentsquare length. Two functions arethen called iteratively as the level isincreased by one each time to fill inthe details of the landscape.This procedure is illustrated inFigure 3. To begin with we have asquare grid with known elevationspreviously calculated for the vertices(i.e., the grey dots in Figure 3(a)). Thecenter points (i.e., the black dots inFigure 3(b)) can be calculated as theaverage elevation of the four adjacentvertices (grey dots) plus a random displacementwith variance (2h 2 ) α whereh is 2 n /2 level , the quartered squarelength. Finally elevations for the midpointsof each side (i.e., the black dotsin Figure 3(c)) can be calculated usingthe average elevation of the four adjacentgrey dots plus a random displacementwith variance (2h 2 ) α as before.The only potential problem occursnear the edges of the grid where somepoints may be missing, but this can beeffectively treated using special cases(e.g., using three instead of four points).4Zooming and CoordinateTransformations in GDI+The good news is that GDI+ providesa matrix class that takes careof most of the details of coordinatetransformations. The bad news is thatapplying methods of the matrix classto produce particular transformationsis not entirely clear from the documentation.However, by clearly statingthe problem we can easily solve it. Inthe context of fractal landscapes wewould like the user to be able to selecta region of interest and zoom in on it.This involves a coordinate transformationbecause we would like what wasdisplayed in a smaller region to bedisplayed in a bigger region.f 4Figure 4: A general coordinatetransformationAUTHOR BIODr. Kieran Mulchrone currentlylectures in Modelling and NumericalComputing in the Department ofApplied Mathematics, UniversityCollege, Cork, Ireland. However, hestarted out life as a geologist beforebecoming a software developer (andshockingly enough for an academic,actually worked in the real world!),and then after all that settled backinto the comfort zone of academia.His research has to do with modellinggeological phenomena such assand ripples, coastal erosion, mudcracks, tectonics, etc. He is marriedwith four children, two dogs, and aTomagotche.4 k.mulchrone@ucc.iedotnetdevelopersjournal.com • June 200511

DNDJ 6-3 web.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 6-3WEB.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 3-11 Nov.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 6-4 web.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 4-9.indd - sys-con.com's archive of magazines - SYS-CON ...
DNDJ 3-7 July.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 1-12 Dec.(NEWCONF - sys-con.com's archive of magazines ...
DNDJ February 3-2.indd - sys-con.com's archive of magazines ...
DNDJ 4-8.indd - sys-con.com's archive of magazines - SYS-CON ...
JDJ 10-10.indd - sys-con.com's archive of magazines - SYS-CON ...
jdjedge conference & expo - sys-con.com's archive of magazines ...
DNDJ 2-2.qxd - sys-con.com's archive of magazines - SYS-CON ...
JDJ 10-6.indd - sys-con.com's archive of magazines - SYS-CON Media
Conclusion - sys-con.com's archive of magazines
SCOTT McNEALY - sys-con.com's archive of magazines - SYS-CON ...
issue 6 - sys-con.com's archive of magazines - SYS-CON Media
DNDJ 2-8.qxd - sys-con.com's archive of magazines - SYS-CON ...
LinuxWorld.com - sys-con.com's archive of magazines - SYS-CON ...
JAVA Vol 3 Issue4 - sys-con.com's archive of magazines
Figure 1 - sys-con.com's archive of magazines - SYS-CON Media
NET - sys-con.com's archive of magazines - SYS-CON Media
CFDJ 8-5.indd - sys-con.com's archive of magazines - SYS-CON ...
LWM 3-12.indd - sys-con.com's archive of magazines - SYS-CON ...
FREE - sys-con.com's archive of magazines - SYS-CON Media
of Wi-Fi - sys-con.com's archive of magazines - SYS-CON Media
JDJ 10-3.indd - sys-con.com's archive of magazines - SYS-CON Media
ISSJ 3-1.indd - sys-con.com's archive of magazines - SYS-CON Media
Web Services Edge 2003 - sys-con.com's archive of magazines ...
Download - sys-con.com's archive of magazines - SYS-CON Media
Download - sys-con.com's archive of magazines - SYS-CON Media