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

public class TrackMaker : MonoBehaviour
{
    public GameObject terrain;
    public Shader drawShader;
    public Transform[] wheels;
    public LayerMask layerMask;
    [Range(0.1f, 2f)]
    public float brushSize = 1;
    [Range(0, 100)]
    public float brushStrength = 100;
    public Texture Brush;
    public bool RadialBrush = true;
    public Texture test;

    private RenderTexture splatMap;
    private Material snowMat;
    private Material drawMat;
    private RaycastHit hit;
    public bool debug = true;
    // Start is called before the first frame update
    void Start()
    {
        //layerMask = LayerMask.GetMask("Ground");
        drawMat = new Material(drawShader);
        snowMat = terrain.GetComponent<MeshRenderer>().material;
        splatMap = new RenderTexture(1024, 1024, 0, RenderTextureFormat.ARGBFloat);
        snowMat.SetTexture("_Splat", splatMap);
        drawMat.SetTexture("_Brush", Brush);
    }
    float frame = 0;
    // Update is called once per frame
    void Update()
    {
        foreach (var wheel in wheels)
        {
            Debug.DrawRay(wheel.position, Vector3.down * 4f, Color.red);
            if (Physics.Raycast(wheel.position, Vector3.down, out hit, 4f, layerMask))
            {
                drawMat.SetVector("_Coordinate", new Vector4(hit.textureCoord.x, hit.textureCoord.y, 0, 0));
                drawMat.SetFloat("_Strength", brushStrength);
                drawMat.SetFloat("_Size", brushSize);
                drawMat.SetFloat("_RadialBrush", RadialBrush ? 1 : 0);
                RenderTexture tmp = RenderTexture.GetTemporary(splatMap.width, splatMap.height, 0, RenderTextureFormat.ARGBFloat);
                Graphics.Blit(splatMap, tmp);
                Graphics.Blit(tmp, splatMap, drawMat);
                RenderTexture.ReleaseTemporary(tmp);
            }
        }
    }

    private void OnGUI()
    {
        if (debug)
            GUI.DrawTexture(new Rect(0, 0, 256 / 2, 256 / 2), splatMap, ScaleMode.ScaleToFit, false, 1);
    }
}
