using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VolumeTerrain {

	private MeshFilter filter;

	public VolumeTerrain() {
		GameObject gameObject = new GameObject();

		MeshRenderer renderer = gameObject.AddComponent (typeof(MeshRenderer)) as MeshRenderer;
		//renderer.material = Resources.Load("Materials/EmptyMaterial", typeof(Material)) as Material;
		renderer.enabled = false;
		filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;

		List<Vector3> vertices = new List<Vector3>();
		List<int> indices = new List<int>();

		for (int i = 0; i < Constants.GRIDE_SIZE; i++) {
			for (int j = 0; j < Constants.GRIDE_SIZE; j++) {

				float x = GameController.minX + i * (GameController.maxX - GameController.minX) / Constants.GRIDE_SIZE;
				float y = GameController.minY + j * (GameController.maxY - GameController.minY) / Constants.GRIDE_SIZE;
				float z = GameController.altitudeAt(new GameVertex (x, y));

				vertices.Add (new Vector3 (x, y, -z));
			}
		}

		for (int i = 0; i < Constants.GRIDE_SIZE - 1; i++) {
			for (int j = 0; j < Constants.GRIDE_SIZE - 1; j++) {
				indices.Add (i * Constants.GRIDE_SIZE + j);
				indices.Add (i * Constants.GRIDE_SIZE + j + 1);
				indices.Add ((i + 1) * Constants.GRIDE_SIZE + j);

				indices.Add ((i + 1) * Constants.GRIDE_SIZE + j + 1);
				indices.Add ((i + 1) * Constants.GRIDE_SIZE + j);
				indices.Add (i * Constants.GRIDE_SIZE + j + 1);
			}
		}


		// Create the mesh
		Mesh mesh = new Mesh();
		mesh.vertices = vertices.ToArray();
		mesh.triangles = indices.ToArray();
		mesh.RecalculateNormals();

		filter.mesh = mesh;

		//Add collider
		MeshCollider collider = gameObject.AddComponent<MeshCollider>();
		collider.sharedMesh = mesh;

		gameObject.layer = 2;
	}
}
