Skip to content

Instantly share code, notes, and snippets.

@SoylentGraham
Created May 3, 2016 22:31
Show Gist options
  • Save SoylentGraham/ba1a29e4c004655f752b10b7722e6209 to your computer and use it in GitHub Desktop.
Save SoylentGraham/ba1a29e4c004655f752b10b7722e6209 to your computer and use it in GitHub Desktop.
Shader based texture painting. Add the script to a plane with a collider and attach a render texture
Shader "NewChromantics/PaintCloudData"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
PaintUv("PaintUv", VECTOR) = (0,0,0,0)
PaintBrushSize("PaintBrushSize", Range(0,0.1) ) = 0.1
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "CloudData.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float PaintBrushSize;
float2 PaintUv;
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
uint3 CloudDataPos = GetCubeDataPos( i.uv );
if ( distance( i.uv, PaintUv ) < PaintBrushSize )
return float4(0,0,0,1);
return tex2D( _MainTex, i.uv );
return float4(1,0,0,1);
}
ENDCG
}
}
}
using UnityEngine;
using System.Collections;
public class PaintMe : MonoBehaviour {
public Material PaintShader;
public RenderTexture PaintTarget;
public RenderTexture TempRenderTarget;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hitInfo = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// OnMouseDown
if (Input.GetMouseButton(0))
{
if (Physics.Raycast(ray, out hitInfo))
{
hitInfo.collider.SendMessage("HandleClick", hitInfo, SendMessageOptions.DontRequireReceiver);
}
}
}
// void OnMouseDown()
void HandleClick(RaycastHit Hit)
{
var LocalHit = transform.worldToLocalMatrix * Hit.point;
var LocalHit3 = new Vector3(LocalHit.x, LocalHit.y, LocalHit.z);
LocalHit3.Scale(transform.localScale);
print("Box Clicked at " + LocalHit3);
// transform to uv
Vector2 LocalHit2 = new Vector2();
LocalHit2.x = 1- (LocalHit3.x + 0.5f);
LocalHit2.y = 1- (LocalHit3.z + 0.5f);
PaintAt(LocalHit2);
}
void PaintAt(Vector2 Uv)
{
Debug.Log("Paint at " + Uv);
if ( TempRenderTarget == null )
{
TempRenderTarget = new RenderTexture(PaintTarget.width, PaintTarget.height, 0);
}
PaintShader.SetVector("PaintUv", Uv);
Graphics.Blit(PaintTarget, TempRenderTarget);
Graphics.Blit(TempRenderTarget,PaintTarget, PaintShader);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment