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

public class TeaSurface : MonoBehaviour
{
    public float TriangleSize = 0.1f;
    public float WorldHeight = 20;

    public void Start()
    {
        var worldWidth = ((float)Screen.width / Screen.height) * WorldHeight;

        var width = (int)Mathf.Ceil(worldWidth / TriangleSize);
        var height = (int)Mathf.Ceil(WorldHeight / TriangleSize);
        var centerOffset = new Vector3(-worldWidth / 2, 0, -WorldHeight / 2);

        var vertices = new Vector3[height * width];
        for (int z = 0; z < height; ++z)
        {
            for (int x = 0; x < width; ++x)
            {
                vertices[z * width + x] = centerOffset + new Vector3(x * TriangleSize, 0, z * TriangleSize);
            }
        }

        var indices = new int[6 * height * width];
        for (int z = 0; z < height - 1; ++z)
        {
            for (int x = 0; x < width - 1; ++x)
            {
                var i = z * width + x;
                indices[6 * i] = i;
                indices[6 * i + 1] = i + width;
                indices[6 * i + 2] = i + 1;
                
                indices[6 * i + 3] = i + 1;
                indices[6 * i + 4] = i + width;
                indices[6 * i + 5] = i + width + 1;
            }
        }

        var uv = new Vector2[height * width];
        var biggerSize = Mathf.Max(width, height);
        for (int z = 0; z < height; ++z)
        {
            for (int x = 0; x < width; ++x)
            {
                uv[z * width + x] = new Vector2((float)x / biggerSize, (float)z / biggerSize);
            }
        }

        var mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = indices;
        mesh.uv = uv;
        mesh.RecalculateNormals();

        var meshFilter = gameObject.AddComponent<MeshFilter>();
        meshFilter.mesh = mesh;
    }
}
