using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace CameraTest
{
	public class Heightmap
	{
		GraphicsDevice gd;
		VertexBuffer buffer;
		IndexBuffer index;

		public Heightmap ( GraphicsDevice _gd, Texture2D map )
		{
			gd = _gd;
			Color [] color = new Color [ map.Width * map.Height ];
			map.GetData<Color> ( color );
			VertexPositionColor [] buffers = new VertexPositionColor [ map.Width * map.Height ];
			buffer = new VertexBuffer ( gd, VertexPositionColor.VertexDeclaration, map.Width * map.Height, BufferUsage.None );

			for ( int z = 0; z < map.Height; z++ )
			{
				for ( int x = 0; x < map.Width; x++ )
				{
					buffers [ z * map.Height + x ].Position.X = x - map.Width / 2.0f;
					buffers [ z * map.Height + x ].Position.Z = z - map.Height / 2.0f;
					buffers [ z * map.Height + x ].Position.Y = color [ z * map.Height + x ].R / 10.0f;
					buffers [ z * map.Height + x ].Color = Color.Yellow;
				}
			}

			buffer.SetData<VertexPositionColor> ( buffers );
			gd.SetVertexBuffer ( buffer );

			short [] indices = new short [ ( map.Width - 1 ) * ( map.Height - 1 ) * 2 * 3 ];
			index = new IndexBuffer ( gd, IndexElementSize.SixteenBits, (map.Width - 1) * (map.Height - 1) * 2 * 3, BufferUsage.None );

			for ( short z = 0; z < map.Height - 1; z++ )
			{
				for ( short x = 0; x < map.Width - 1; x++ )
				{
					indices [ x * 6 + 0 ] = ( short ) ( z * map.Width + x );
					indices [ x * 6 + 1 ] = ( short ) ( z * map.Width + x + 1 );
					indices [ x * 6 + 2 ] = ( short ) ( ( z + 1 ) * map.Width + x );

					indices [ x * 6 + 3 ] = ( short ) ( ( z + 1 ) * map.Width + x );
					indices [ x * 6 + 4 ] = ( short ) ( z * map.Width + x + 1 );
					indices [ x * 6 + 5 ] = ( short ) ( ( z + 1 ) * map.Width + x + 1 );
				}
			}

			index.SetData<short> ( indices );
			gd.Indices = index;
		}

		public void Draw ()
		{
			gd.DrawPrimitives ( PrimitiveType.TriangleList, 0, buffer.VertexCount / 3 );
		}
	}
}
