set display mode 1280, 1024, 32
sync on
sync rate 0
backdrop on
color backdrop 0
 
 
#CONSTANT imgX 128
#CONSTANT imgY 128
 
oX = 0
oY = 0
generateTerrain(0,0)
 
`set sprite uv
frameTime# = 1.0
startTime = timer()
do
   frameTime# = (frameTime# * 0.8) + ((timer() - startTime) * 0.2)
   startTime = timer()
 
   if leftkey()  then dec oX : generateTerrain(oX, oY)
   if rightkey() then inc oX : generateTerrain(oX, oY)
   if upkey()    then dec oY : generateTerrain(oX, oY)
   if downkey()  then inc oY : generateTerrain(oX, oY)
 
 
   paste image 1, 0, 0
   sync
loop
end
 
 
function generateTerrain(offsetX, offsetY)
   if memblock exist(1) = 0
      make memblock 1, 12 + (imgX * imgY * 4)
      write memblock dword 1, 0, imgX
      write memblock dword 1, 4, imgY
      write memblock dword 1, 8, 32
   endif
 
 
   for x = 0 to imgX-1
      for y = 0 to imgY-1
         v# = (PerlinNoise_2D(x + offsetX, y + offsetY) + 1.0) * 127.0
         write memblock dword 1, 12 + ((y*imgX) + x)*4, rgb(v#, v#, v#)
         if escapekey() then end
      next y
   next x
 
   make image from memblock 1, 1
endfunction
 
 
 
`Linear Interpolation... Not the best - but damn quick!
function Interpolate(a#, b#, x#)
   v# = (a# * (1.0 - x#) + b# * x#)
endfunction v#
 
 
 
 
 
function Noise(x,y)
   n as DWORD
   n = x + y * 57
   `text 0, 20, "result: " + str$(n)
   `n = (n << 13) ^ n
   `text 0, 30, "result: " + str$(n)
   result# = (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) && 0x7fffffff) / 1073741824.0)
 
endfunction result#
 
 
 
 
function SmoothedNoise(x, y)
   corners# = ( Noise(x-1,y-1)+Noise(x+1,y+1)+Noise(x+1,y-1)+Noise(x-1,y+1) ) / 16.0
   sides#   = ( Noise(x-1,y  )+Noise(x+1,y  )+Noise(x  ,y-1)+Noise(x  ,y+1) ) /  8.0
   center#  = ( Noise(x  ,y  ) ) / 4.0
   v# = corners#+sides#+center#
endfunction v#
 
 
 
 
 
 
`Produce interpolated noise for pixel x, y
function InterpolatedNoise(x#, y#)
remstart
   intX = int(x#)
   fracX# = x# - intX
 
   intY = int(y#)
   fracY# = y# - intY
   v1# = SmoothedNoise(IntX  , intY  )
   v2# = SmoothedNoise(IntX+1, intY  )
   v3# = SmoothedNoise(IntX  , intY+1)
   v4# = SmoothedNoise(IntX+1, intY+1)
 
   i1# = Interpolate(v1#, v2#, fracX#)
   i2# = Interpolate(v3#, v4#, fracX#)
 
   final# = Interpolate(i1#, i2#, fracY#)
remend
   final# = SmoothedNoise(x#, y#)
endfunction final#
 
 
 
 
 
 
`Produce noise for pixel x,y
function PerlinNoise_2D(x, y)
   total# = 0
   `Persistance
   p# = 0.25
   `Number of Octaves
   n = 1
 
   for i = 0 to n-1
      frequency# = 2.0 ^ i
      amplitude# = p# ^ i
 
      inc total#, InterpolatedNoise(x * frequency#, y * frequency#) * amplitude#
   next i
endfunction total#