参考自:冯乐乐的博客 http://blog.csdn.net/candycat1992/article/details/44039077
(1)CG 头文件 ShaderToyDefines.cginc
/* ------------------------ Shader Toy 着色器输入 -----------------------------------
uniform vec3 iResolution; // viewport resolution (in pixels)
uniform float iGlobalTime; // shader playback time (in seconds)
uniform float iTimeDelta; // render time (in seconds)
uniform int iFrame; // shader playback frame
uniform float iChannelTime[4]; // channel playback time (in seconds)
uniform vec3 iChannelResolution[4]; // channel resolution (in pixels)
uniform vec4 iMouse; // mouse pixel coords. xy: current (if MLB down), zw: click
uniform samplerXX iChannel0..3; // input channel. XX = 2D/Cube
uniform vec4 iDate; // (year, month, day, time in seconds)
uniform float iSampleRate; // sound sample rate (i.e., 44100)
-------------------------------------------------------------------------------------*/
// 定义一系列宏和 Shader Toy 中的 GLSL 衔接
#define vec2 float2
#define vec3 float3
#define vec4 float4
#define mat2 float2x2
#define mat3 float3x3
#define mat4 float4x4
#define iGlobalTime _Time.y
#define mod fmod
#define mix lerp
#define fract frac
#define texture2D tex2D
#define iResolution _ScreenParams
#define gl_FragCoord ((_iParam.scrPos.xy / _iParam.scrPos.w) * _ScreenParams.xy)
#define PI2 6.28318530718
#define pi 3.14159265358979
#define halfpi (pi * 0.5)
#define oneoverpi (1.0 / pi)
(1)Shader 文件如下:
Shader "Shader/Template" {
Properties {
}
CGINCLUDE
#include "UnityCG.cginc"
#include "ShaderToyDefines.cginc"
#pragma target 3.0
// Properties
struct v2f {
float4 pos : SV_POSITION;
float4 scrPos : TEXCOORD0;
};
v2f vert(appdata_base v) {
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.scrPos = ComputeScreenPos(o.pos);
return o;
}
vec4 main(vec2 fragCoord);
fixed4 frag(v2f _iParam) : COLOR0 {
return main(gl_FragCoord);
}
// 函数 main 对应了 ShaderToy 的 mainImage 函数
vec4 main(vec2 fragCoord) {
return vec4(1, 1, 1, 1);
}
ENDCG
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
ENDCG
}
}
FallBack Off
}
(2)如果要使用到鼠标点击行为,使用的脚本
using UnityEngine;
using System.Collections;
/// <summary>
/// 把该脚本拖拽到材质所在的物体上,同时保证该物体上绑定了 Collider
/// </summary>
public class ShaderToyHelper : MonoBehaviour
{
private Material _material = null;
private bool _isDragging = false;
void Start()
{
Renderer render = GetComponent<Renderer>();
if (render != null)
_material = render.material;
_isDragging = false;
}
void Update()
{
Vector3 mousePosition = Vector3.zero;
// 在有鼠标拖拽时,mousePosition 的 Z 分量为 1, 否则为 0,与 ShaderToy 中判断鼠标的方式一致
if (_isDragging)
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f);
else
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.0f);
if (_material != null)
_material.SetVector("iMouse", mousePosition);
}
void OnMouseDown() {
_isDragging = true;
}
void OnMouseUp() {
_isDragging = false;
}
}