using UnityEngine;
using System.Collections;

public class L05_User : MonoBehaviour 
{

	[SerializeField]
	private Camera renderCamera;

	[SerializeField]
	private Shader paintShader;

	[SerializeField]
	private float Radius = 0.1f;

	private Vector4 center = new Vector4();

	// Use this for initialization
	void Start () 
	{
		if (renderCamera == null || paintShader == null )
			return;

		//Graphics.SetRenderTarget(renderCamera.targetTexture);
		RenderTexture.active = renderCamera.targetTexture;
		GL.Clear(false, true, Color.clear);

		renderCamera.aspect = 3;
		Camera.main.aspect = 3;
		renderCamera.SetReplacementShader(paintShader, null);
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (renderCamera == null || paintShader == null)
			return;

		if( Input.GetMouseButton(0) )
		{
			Vector3 screenMousePos = Input.mousePosition;

			center.x = (screenMousePos.x / Screen.width - 0.5f) * 2;
			center.y = (screenMousePos.y / Screen.height - 0.5f) * 2;

			Shader.SetGlobalFloat("radius", Radius);
			Shader.SetGlobalVector("center", center);

			// If we want to render in wireframe mode with this camera
			//GL.wireframe = true;
			renderCamera.SetReplacementShader(paintShader, null);
			renderCamera.Render();
		}

		// Save texture as PNG on right mouse click
		/*
		if (Input.GetMouseButtonDown(1))
		{
			int width = renderCamera.targetTexture.width;
			int height = renderCamera.targetTexture.height;
			RenderTexture.active = renderCamera.targetTexture;
			Texture2D saveTexture =
				new Texture2D(width, height, TextureFormat.RGB24, false);
			saveTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);

			RenderTexture.active = null; //can help avoid errors 
			byte[] bytes;
			bytes = saveTexture.EncodeToPNG();
			System.IO.File.WriteAllBytes(
				"Assets/rendertexture.png", bytes);
		}
		*/
	}
}
