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

public class CubeMap : MonoBehaviour
{
    public Shader DepthShader;
    public RenderTexture DepthMap;

    private Camera depthCamera;

    void Start()
    {
        depthCamera = gameObject.AddComponent<Camera>();
        
        depthCamera.enabled = false;
        depthCamera.farClipPlane = 12;
        depthCamera.nearClipPlane = 0.03f;
        depthCamera.backgroundColor = Color.white;

        //Shader.SetGlobalTexture("_LightCube", DepthMap);
    }

    // Update is called once per frame
    void Update()
    {
        // note: w is farplane
        Shader.SetGlobalVector("_LightMapCameraPos", new Vector4(transform.position.x, transform.position.y, transform.position.z, depthCamera.farClipPlane));
        

        depthCamera.SetReplacementShader(DepthShader, "");

        if (!depthCamera.RenderToCubemap(DepthMap))
        {
            Debug.LogError("Failed cubemap render");
        }

        depthCamera.ResetReplacementShader();

        //see.targetTexture = null;

        //see.targetTexture = SanityMap;
        //see.Render();
        //see.targetTexture = null;

        //see.Render();

        //if (tex == null)
        //{
        //    tex = new Texture2D(1024, 1024, TextureFormat.ARGB32, false);
        //}
        //
        //
        //RenderTexture.active = SeeMap;
        //tex.ReadPixels(new Rect(0, 0, 1024, 1024), 0, 0);
        //RenderTexture.active = null;
        //byte[] png = tex.EncodeToPNG();
        //FileStream f = File.Open("test.png", FileMode.OpenOrCreate);
        //f.Write(png, 0, png.Length);
        //f.Close();

        //see.transform.forward = Vector3.forward;
        //see.transform.up = Vector3.up;
        //see.rect = new Rect(0, 0.5f, 0.25f, 0.5f);
        //see.Render();
        //
        //see.transform.forward = Vector3.right;
        //see.rect = new Rect(0.25f, 0.5f, 0.25f, 0.5f);
        //see.Render();
        //
        //see.transform.forward = Vector3.back;
        //see.rect = new Rect(0.5f, 0.5f, 0.25f, 0.5f);
        //see.Render();
        //
        //see.transform.forward = Vector3.left;
        //see.rect = new Rect(0.75f, 0.5f, 0.25f, 0.5f);
        //see.Render();
        //
        //see.transform.forward = Vector3.down;
        //see.transform.up = Vector3.forward;
        //see.rect = new Rect(0, 0, 0.25f, 0.5f);
        //see.Render();
        //
        //see.transform.forward = Vector3.up;
        //see.transform.up = Vector3.back;
        //see.rect = new Rect(0.25f, 0, 0.25f, 0.5f);
        //see.Render();


    }
}
