如果你會看這篇文章,代表你玩 Unity 已經玩到很深入了,CPU 計算已經不能滿足你,這時你不得不把注意力轉到 GPU 身上。GPU 的介紹就不用我多說了,就是超越CPU的存在。如果用 Texture2D 來畫你想要的圖案速度會慢的驚人,如果你用 Shader ( GPU ) 來畫將會快上幾千倍,好了,唬爛就到此為止,我們回歸正題。
這是一個簡單 Unity 的 GPGPU 計算,使用 ComputeShader。將輸入的數字丟入GPU,然後乘以兩倍再傳回 CPU。你可以往下拉直接看結果圖,就明白我再說什麼了。
注意:ComputeShader 只能在 Dx11 的顯卡上執行,除了 Windows 7 + 以外,一些新型的 Android 設備也能跑,要看你設備的 GPU 有沒有支持 Dx11。我目前測過以下設備都能跑: 華為 P10 Plus ( CPU : 麒麟960,GPU : Mali-G71 MP8 )、Asus zenfone 3 Deluxe ( CPU : 驍龍821, GPU : Adreno 530 )。
C # :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public ComputeShader shader;
struct Data{
public float A;
public float B;
public float C;
}
void Start ()
{
Data [] inputData = new Data[3];
Data [] outputData = new Data[3];
print ("輸入 --------------------------------------------");
for(int i=0; i <inputData.Length; i++){
inputData[i].A = i * 3 + 1;
inputData[i].B = i * 3 + 2;
inputData[i].C = i * 3 + 3;
print (inputData[i].A + ", " + inputData[i].B + ", " + inputData[i].C);
}
// Data 有3個float,一個 float 有 4 Byte,所以 3 * 4 = 12
ComputeBuffer inputbuffer = new ComputeBuffer(outputData.Length, 12);
ComputeBuffer outputbuffer = new ComputeBuffer(outputData.Length, 12);
int k = shader.FindKernel ("CSMain");
// 寫入 GPU
inputbuffer.SetData(inputData);
shader.SetBuffer(k, "inputData", inputbuffer);
// 計算,並輸出至 CPU
shader.SetBuffer(k, "outputData", outputbuffer);
shader.Dispatch(k, outputData.Length, 1,1);
outputbuffer.GetData (outputData);
print ("輸出 --------------------------------------------");
// 打印結果
for(int i=0; i < outputData.Length; i++){
print(outputData [i].A + ", " + outputData [i].B + ", " + outputData [i].C);
} // 釋放
inputbuffer.Dispose ();
outputbuffer.Dispose ();
}
}
ComputeShader :
#pragma kernel CSMain
struct Data{
float A;
float B;
float C;
};
// 從 CPU 寫入進來的資料 ( CPU -> GPU )
StructuredBuffer<Data> inputData;
// outputData 之後會丟回 CPU ( GPU -> CPU )
RWStructuredBuffer<Data> outputData;
[numthreads(12,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
// 計算完丟回 CPU
outputData[id.x].A = inputData[id.x].A * 2;
outputData[id.x].B = inputData[id.x].B * 2;
outputData[id.x].C = inputData[id.x].C * 2;
}
結果 :
————————————————
原文链接:https://blog.csdn.net/weixin_38884324/article/details/79284373