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源码,布布扣,bubuko.com

时间: 2024-10-22 14:35:11

Unity3d 镜面折射 vertex and frag Shader源码的相关文章

Unity3d 镜面反射 vertex and frag Shader源码

Unity3d 镜面反射 网上能找到的基本上是固定管道或表面渲染的shader, 特此翻译为顶点.片段渲染的Shader, 本源码只涉及shader与cs部分, Editor部分使用NGUI绘制的, 请自行下载NGUI unity3d 版本:v4.3.1 ReflectionEffect.cs using UnityEngine; using System.Collections; using System; /// <summary> /// 反射效果 /// </summary>

unity 内置 shader 源码

接下来的几天会写几个shader,这里先给出参考资料, 吃饱后补充shader的详解 unity built-in shader 源码(不同uinty版本): 下载地址:http://unity3d.com/unity/download/archive

OpenGL Shader源码分享

Opengl shader程序,旗帜混合纹理加载,通过N张图片,能够组合出数百个:http://www.eyesourcecode.com/thread-39015-1-1.html 用GLSL做了一个可以描出物体的边的shader:http://www.eyesourcecode.com/thread-41503-1-1.html GLSL SHADER实现的机器人,手臂可以动:http://www.eyesourcecode.com/thread-21261-1-1.html 更多OpenG

Unity3d 镜面反射 vertex and frag Shader源代码

Unity3d 镜面反射 网上能找到的基本上是固定管道或表面渲染的shader. 特此翻译为顶点.片段渲染的Shader, 本源代码仅仅涉及shader与cs部分. Editor部分使用NGUI绘制的, 请自行下载NGUI unity3d 版本号:v4.3.1 ReflectionMirror.cs using UnityEngine; using System.Collections; using System; /// <summary> /// 反射效果 /// </summary

unity, 查看内置shader源码

1,建一个球体. 2,建一个材质,将材质拖到球体上. 3,在材质的shader下拉列表中选择想查看的内置shader,点材质栏右上设置按钮->Select Shader 进入shader面板. 4,点Compile and show code查看shader代码.(在此之前可点按钮右边箭头在弹出的下拉菜单中设置编译的目标平台). 不理想的是编译出来的代码可能是平台相关的,而且可读性也不大好. 不知道如何查看编译前的原始CG代码.

Unity中内置Shader源码的获取方式

现在可以直接在Unity下载页面获得 http://unity3d.com/get-unity/download/archive 包括StandardShader,StandardShaderGUI.cs等

Unity3D游戏完整源码

自学Unity3D比较辛苦和困难,给大家推荐一些Unity3D资源,与君共勉. Unity3D 3d射击游戏源码 EZFPS Multiplayer FPS Kithttp://www.idoubi.net/unity3d/complete-project/282.htmlUnity3D 暴力之城游戏源码 Full Game Kit – Hammer 2http://www.idoubi.net/unity3d/complete-project/279.htmlUnity3D 2D射击游戏模板

2020年3月份Unity3D游戏源码合集-免费下载

新找到一些Unity游戏源码,都是能免费下载的,喜欢的千万不要错过. Unity3D 低模射击游戏模板 完整源码 Low Poly FPS Packhttp://www.idoubi.net/unity3d/complete-project/6310.html Unity3D AR生存射击游戏 完整源码 AR Survival Shooter- AR FPS — Augmented Reality — AR Shooter v2.3http://www.idoubi.net/unity3d/co

Unity3d 实时折射与反射

这里只贴出了实时折射与反射的脚本与shader, 关于NGUI部分则请大家自行下载. 这个版本主要缺点是折射部分平面的Layer必须是water层,如果有哪位高手能把这一块去掉,请记得把代码回复到这篇文章下,谢谢! Water.cs using UnityEngine; using System.Collections; using System; using System.Collections.Generic; /// <summary> /// 水面 /// </summary&g