Compute Shader in Unity Part2 ——Texture

Texture 在Compute Shader 中算是一个特别重要的应用了。

其实原理什么的都和上一篇说的一样。

下面说一些不一样的。
 

#pragma kernel CSMain
 
RWTexture2D Result;

[numthreads(8,8,1)]
void CSMain (uint2 id : SV_DispatchThreadID)
{
    float x, y;
    Result.GetDimensions(x, y);
    Result[id] = float4(id.x/x,id.y/y,1,1);

}

-------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class _t2 : MonoBehaviour {
    public RawImage ri;
    public ComputeShader shader;
    RenderTexture tex;
	void Start () {
        tex = new RenderTexture(64,64,0);
        tex.enableRandomWrite = true;
        tex.Create();
        
        shader.SetTexture(0, "Result", tex);
        shader.Dispatch(0, 8, 8, 1);
        ri.texture = tex;
	}

    private void OnDestroy()
    {
        tex.Release();
    }
}

1.RWTexture2D Result;      表示可随机写入的Texture。

2.Result.GetDimensions(x,y)        获取高和宽。

3.tex.enableRandomWrite = true; 一定要将RenderTexture的随机读写打开。

下面说一下Texture 在Compute Shader 中的采样:

在此之前 ,先说一下所有继承于Texture的类都可以用于compute shader中的计算。

1.最简单的一种采样:float4 t=tex[id]

2.带mipmap的采样:float4 t=tex.mips[0][id]  或 tex.Load(uint3(id,0));  这里level为0,代表原图。

3.使用SamplerState(采样器)进行采样。

SamplerState Sampler0
{
    Filter = MIN_MAG_MIP_LINEAR;
};
SamplerState Sampler1
{
    Filter = MIN_LINEAR_MAG_MIP_POINT;
};

float4 t = tex.SampleLevel(Sampler0, uv, 0);

0为mipmap的level,uv即采样uv。

 

你可能感兴趣的:(Unity,Shader)