#Simple python script that generates a terragen script
#it diveides terrain up in spots, and looks from each spot into multiple directions


terrainsize=503
step=10  #int(raw_input('step: '))
nrdirections=8
height=5 #gets overridden by height map
margin=50

terrainunits=1024 #just a 'wild' guess...

print 'this script uses a 16-bit intel byte order heightmap as you can export from terragen'
print 'Opening height map'
hm = open ("heightmap.bin", 'rb')

print 'Generating terrain script'
print 'size', terrainsize
print 'step', step
print 'number directions', nrdirections

print 'this generates about', round(((terrainsize-2*margin)*(terrainsize-2*margin))/(step*step))*nrdirections, 'images'

f=open ("terragen.tgs", "w+")

f.write (";Auto generated terragen script"+'\r\n')
f.write ("; We don't adjust world settings like banking or waterlevel"+'\r\n')

f.write ('initanim "C:\\terragen\\project\\frame", 1\r\n')
#f.write ('WaterLevel 1.0\r\n')


frame=0
x=margin
while x<(terrainsize-margin):
   print '\r', round(100.0*x/terrainsize), '% done',
   y=margin
   while y<(terrainsize-margin):
      #read height from heightmap file
      sk = 1 + 2 * (y * terrainsize + x)
      #print 'seek ',sk
      hm.seek (sk, 0)
      hb=hm.read (1)
      lb=hm.read (1)
      hgt = (256 * ord(hb) + ord (lb)) / terrainunits
      height = hgt + 1
      #print 'height ', hgt
      for c in range(nrdirections):
         camdir = 360 * c / 8
#         l='Campos '+str(x)+' '+str(y)
         frame=frame+1
         f.write ('\r\n; Frame '+str(frame)+'\r\n')
         f.write ('CamPos '+str(x)+','+str(y)+','+str(height)+'\r\n')
         f.write ('CamH '+str(camdir)+'\r\n')
         f.write ('CamP -3\r\n')
         f.write ('FRend\r\n')
      y=y+step
   x=x+step



f.close()
hm.close()


print str(frame)+' frames written'
print 'enter to terminate'


i=raw_input()

print 'bye'




