unity3d 在shader中创建及使用Texture3D

130 篇文章 5 订阅

代码来自Aras

Texture3D必须要在脚本中创建

c#:

<span style="font-size:14px;"> 
using UnityEngine;
 
public class Create3DTex : MonoBehaviour {
   
    public Texture3D tex;
    public int size = 16;
 
    void Start ()
    {
        tex = new Texture3D (size, size, size, TextureFormat.ARGB32, true);
        var cols = new Color[size*size*size];
        float mul = 1.0f / (size-1);
        int idx = 0;
        Color c = Color.white;
        for (int z = 0; z < size; ++z)
        {
            for (int y = 0; y < size; ++y)
            {
                for (int x = 0; x < size; ++x, ++idx)
                {
                    c.r = ((x1)!=0) ? x*mul : 1-x*mul;
                    c.g = ((y1)!=0) ? y*mul : 1-y*mul;
                    c.b = ((z1)!=0) ? z*mul : 1-z*mul;
                    cols[idx] = c;
                }
            }
        }
        tex.SetPixels (cols);
        tex.Apply ();
        renderer.material.SetTexture ("_Volume", tex);
    }  
}
 </span>
JS:

<span style="font-size:14px;">function CreateIdentityLut (dim : int, tex3D : Texture3D) 
{
  var newC : Color[] = new Color[dim * dim * dim];
  var oneOverDim : float = 1.0f / (1.0f * dim - 1.0f);
  for(var i : int = 0; i < dim; i++) {
    for(var j : int = 0; j < dim; j++) {
      for(var k : int = 0; k < dim; k++) {
        newC[i + (j*dim) + (k*dim*dim)] = new Color((i*1.0f)*oneOverDim, (j*1.0f)*oneOverDim, (k*1.0f)*oneOverDim, 1.0f);
      }
    }
  }
  tex3D.SetPixels (newC);
  tex3D.Apply ();
}
</span>



shader:

<span style="font-size:14px;">         
        Shader "DX11/Sample 3D Texture" {
        Properties {
            _Volume ("Texture", 3D) = "" {}
        }
        SubShader {
        Pass {
         
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma exclude_renderers flash gles
         
        #include "UnityCG.cginc"
         
        struct vs_input {
            float4 vertex : POSITION;
        };
         
        struct ps_input {
            float4 pos : SV_POSITION;
            float3 uv : TEXCOORD0;
        };
         
         
        ps_input vert (vs_input v)
        {
            ps_input o;
            o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
            o.uv = v.vertex.xyz*0.5+0.5;
            return o;
        }
         
        sampler3D _Volume;
         
        float4 frag (ps_input i) : COLOR
        {
            return tex3D (_Volume, i.uv);
        }
         
        ENDCG
         
        }
        }
         
        Fallback "VertexLit"
        }
         

     

</span>


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值