Unity3d 镜面折射 vertex and frag Shader源代码
Unity3d 镜面折射
网上能找到的基本上是固定管道或表面渲染的shader。
特此翻译为顶点、片段渲染的Shader,
本源代码仅仅涉及shader与cs部分,
请自行下载NGUI
unity3d 版本号:v4.3.1
RefractionMirror.cs
using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// 镜面折射效果
/// </summary>
[AddComponentMenu("GameCore/Effect/Refraction/Mirror")]
[ExecuteInEditMode]
public class RefractionMirror : MonoBehaviour
{
public bool DisablePixelLights = true;
public int TextureSize = 512;
public float ClipPlaneOffset = 0;
public LayerMask ReflectLayers = -1;
private Hashtable _RefractionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture _RefractionTexture = null;
private int _OldRefractionTextureSize = 0;
private static bool _InsideRendering = false;
// This is called when it's known that the object will be rendered by some
// camera. We render Refractions and do other updates here.
// Because the script executes in edit mode, Refractions for the scene view
// camera will just work!
void OnWillRenderObject()
{
if (!enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled)
return;
Camera cam = Camera.current;
if (!cam)
return;
// Safeguard from recursive Refractions.
if (_InsideRendering)
return;
_InsideRendering = true;
Camera RefractionCamera;
CreateMirrorObjects(cam, out RefractionCamera);
// find out the Refraction plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for Refraction
int oldPixelLightCount = QualitySettings.pixelLightCount;
if (DisablePixelLights)
QualitySettings.pixelLightCount = 0;
CoreTool.CloneCameraModes(cam, RefractionCamera);
RefractionCamera.cullingMask = ~(1 << 4) & ReflectLayers.value; // never render water layer
RefractionCamera.targetTexture = _RefractionTexture;
RefractionCamera.transform.position = cam.transform.position;
RefractionCamera.transform.eulerAngles = cam.transform.eulerAngles;
RefractionCamera.Render();
Material[] materials = renderer.sharedMaterials;
foreach (Material mat in materials)
{
if (mat.HasProperty("_RefractionTex"))
mat.SetTexture("_RefractionTex", _RefractionTexture);
}
// Set matrix on the shader that transforms UVs from object space into screen
// space. We want to just project Refraction texture on screen.
Matrix4x4 scaleOffset = Matrix4x4.TRS(
new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f));
Vector3 scale = transform.lossyScale;
Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z));
mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
foreach (Material mat in materials)
{
mat.SetMatrix("_ProjMatrix", mtx);
}
// Restore pixel light count
if (DisablePixelLights)
QualitySettings.pixelLightCount = oldPixelLightCount;
_InsideRendering = false;
}
// Cleanup all the objects we possibly have created
void OnDisable()
{
if (_RefractionTexture)
{
DestroyImmediate(_RefractionTexture);
_RefractionTexture = null;
}
foreach (DictionaryEntry kvp in _RefractionCameras)
DestroyImmediate(((Camera)kvp.Value).gameObject);
_RefractionCameras.Clear();
}
// On-demand create any objects we need
private void CreateMirrorObjects(Camera currentCamera, out Camera RefractionCamera)
{
RefractionCamera = null;
// Refraction render texture
if (!_RefractionTexture || _OldRefractionTextureSize != TextureSize)
{
if (_RefractionTexture)
DestroyImmediate(_RefractionTexture);
_RefractionTexture = new RenderTexture(TextureSize, TextureSize, 0);
_RefractionTexture.name = "__MirrorRefraction" + GetInstanceID();
_RefractionTexture.isPowerOfTwo = true;
_RefractionTexture.hideFlags = HideFlags.DontSave;
_RefractionTexture.antiAliasing = 4;
_RefractionTexture.anisoLevel = 0;
_OldRefractionTextureSize = TextureSize;
}
// Camera for Refraction
RefractionCamera = _RefractionCameras[currentCamera] as Camera;
if (!RefractionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject("Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
RefractionCamera = go.camera;
RefractionCamera.enabled = false;
RefractionCamera.transform.position = transform.position;
RefractionCamera.transform.rotation = transform.rotation;
RefractionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
_RefractionCameras[currentCamera] = RefractionCamera;
}
}
}
shader
Shader "GameCore/Mobile/Refraction/Mirror"
{
Properties {
_RefractionTex ("Refraction", 2D) = "white" {TexGen ObjectLinear }
_RefractionColor("Color",Color) = (1,1,1,1)
}
SubShader {
Tags {
"RenderType"="Opaque"}
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform float4x4 _ProjMatrix;
uniform sampler2D _RefractionTex;
float4 _RefractionColor;
struct outvertex {
float4 pos : SV_POSITION;
float3 uv : TEXCOORD0;
float4 posProj;
};
outvertex vert(appdata_tan v) {
outvertex o;
o.pos = mul (UNITY_MATRIX_MVP,v.vertex);
o.posProj = mul(_ProjMatrix, v.vertex);
return o;
}
float4 frag(outvertex i) : COLOR {
half4 reflcol = tex2D(_RefractionTex,float2(i.posProj) / i.posProj.w);
return reflcol*_RefractionColor;
}
ENDCG
}
}
}
Shader "GameCore/Refraction/Mirror"
{
Properties {
_RefractionTex ("Refraction ", 2D) = "white" {TexGen ObjectLinear }
_RefractionColor("Color",Color) = (1,1,1,1)
}
SubShader {
Tags {
"RenderType"="Opaque"}
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform float4x4 _ProjMatrix;
uniform sampler2D _RefractionTex;
float4 _RefractionColor;
struct outvertex {
float4 pos : SV_POSITION;
float3 uv : TEXCOORD0;
};
outvertex vert(appdata_tan v) {
outvertex o;
o.pos = mul (UNITY_MATRIX_MVP,v.vertex);
float3 viewDir = ObjSpaceViewDir(v.vertex);
o.uv = mul(_ProjMatrix,float4(viewDir,0));
return o;
}
float4 frag(outvertex i) : COLOR {
half4 reflcol = tex2Dproj(_RefractionTex,i.uv);
return reflcol*_RefractionColor;
}
ENDCG
}
}
}
Unity3d 镜面折射 vertex and frag Shader源代码的更多相关文章
- Unity3d 镜面反射 vertex and frag Shader源代码
Unity3d 镜面反射 网上能找到的基本上是固定管道或表面渲染的shader. 特此翻译为顶点.片段渲染的Shader, 本源代码仅仅涉及shader与cs部分. Editor部分使用NGUI绘制的 ...
- Unity3d 实时折射和反射
这里只是张贴在实时折射和脚本反思shader, 大约NGUI第一部分请下载. 这个版本的主要缺点是折射平面部Layer必须是water层.假设有专家谁可以摆脱这一个.请记得把代码回该条,谢谢! Wat ...
- UnityShader之顶点片段着色器Vertex and Fragment Shader【Shader资料】
顶点片段着色器 V&F Shader:英文全称Vertex and Fragment Shader,最强大的Shader类型,也是我们在使用ShaderLab中的重点部分,属于可编程管线,使用 ...
- Unity3D for VR 学习(9): Unity Shader 光照模型 (illumination model)
关于光照模型 所谓模型,一般是由学术算法发起, 经过大量实际数据验证而成的可靠公式 现在还记得2009年做TD-SCDMA移动通信算法的时候,曾经看过自由空间传播模型(Free space propa ...
- Vertex And Fragment Shader(顶点和片段着色器)
Vertex And Fragment Shader(顶点和片段着色器) Shader "Unlit/ Vertex_And_Fragment_Shader " { Proper ...
- ShaderLab中vertex fragment类Shader基础格式笔记
//U3D用的shader语言叫ShaderLab,基础语法官方文档地址 //https://docs.unity3d.com/Manual/SL-Shader.html //开头指明名字,可以在别的 ...
- Vertex and Fragment Shader
Semantics语义词: 定义:GPU工作时,数据通常暂存在寄存器,那么在Cg中,语义词就指定了输入/输出数据和图形硬件寄存器之间的映射关系. 原理:根据输入语义,图形处理器从某个寄存器取数据:然后 ...
- Unity3D for VR 学习(8): Unity Shader概述
从西安到北京高铁上,一位VR老外团队的华人leader对VR技术做了画龙点睛: “3D游戏的核心部分在Render, 国内很多团队美术.程序中间缺失严重.所以3d游戏做不好. VR这块更是至关重要.” ...
- 3D Computer Grapihcs Using OpenGL - 07 Passing Data from Vertex to Fragment Shader
上节的最后我们实现了两个绿色的三角形,而绿色是直接在Fragment Shader中指定的. 这节我们将为这两个三角形进行更加自由的着色——五个顶点各自使用不同的颜色. 要实现这个目的,我们分两步进行 ...
随机推荐
- JAVA对URL的解码【转】
前段时间做URL的中文转换,有些url是utf8的格式,有的是gb2312的格式,很难区分到底是utf8还是gb2312,找了好久,发现网上的一个牛人写的转换代码: package org.apach ...
- iOS 9: UIStackView入门
本文转自http://www.cocoachina.com/ios/20150623/12233.html 本文由CocoaChina译者candeladiao翻译,欢迎参加我们的翻译活动.原文:iO ...
- Esper学习之二:事件类型
Esper对事件有特殊的数据结构约定.能处理的事件结构有:POJO,java.util.Map,Object Array,XML 1.POJO 对于POJO,Esper要求对每一个私有属性要有gett ...
- 【大数据系列】Hive安装及web模式管理
一.什么是Hive Hive是建立在Hadoop基础常的数据仓库基础架构,,它提供了一系列的工具,可以用了进行数据提取转化加载(ETL),这是一种可以存储.查询和分析存储在Hadoop中的按规模数据的 ...
- 【Ubuntu】更新系统时出现Hash校验和不符的错误(已解决)
在使用 sudo apt-get update && sudo apt-get upgrade 命令更新系统时出现类似这样的错误信息: W: 无法下载 bzip2:/var/lib/a ...
- js 判断数组重复元素以及重复的个数
知识点: .sort()方法用于对数组元素排序,并返回数组. var _arr = ['旅行箱', '旅行箱', '小米', '大米']; var _res = []; // _arr.sort(); ...
- 题目1100:最短路径(最短路径问题进阶dijkstra算法)
题目链接:http://ac.jobdu.com/problem.php?pid=1100 详细链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...
- Linux下应急工具
Linux下的应急工具 在Linux下,应急的查看点无非那个几个,一是看表现(宕机.高CPU.高内存.高IO.高网络通信),二看连接.三看进程.四看日志.五看文件(Linux一切皆文件),再者结合起来 ...
- 【STL】vector的insert方法详解
#include<vector> #include<iostream> using namespace std; int main() { vector<int> ...
- Linux批量杀死进程
杀死进程在linux中使用kill命令了,我们可以下面来给各位介绍一篇关于Linux下批量杀死进程的例子,希望此例子可以对各位同学带来帮助的哦. 批量杀死包含关键字“php-fpm”的进程. kill ...