ComputeShader中Consume與AppendStructuredBuffer的使用

上個月寫了一篇使用像素shader返回累加信息的Trick:http://www.javashuo.com/article/p-ylsmxrlw-cs.htmlhtml

後來無心中發現DX11/Compute shader有一類Append/Consume數據格式更適合這類操做。windows

 

c sharp腳本:app

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ComputeShaderTest : MonoBehaviour
{
    public ComputeShader computeShader;


    void Awake()
    {
        //reference: https://answers.unity.com/questions/1035132/how-can-i-read-in-the-actual-elements-from-an-appe.html

        var kernelID = computeShader.FindKernel("CSMain");
        var appendBuffer = new ComputeBuffer(64, sizeof(int), ComputeBufferType.Append);
        appendBuffer.SetCounterValue(0);
        //定義了緩衝區長度爲64*結構大小的appendBuffer.

        var consumeBuffer = new ComputeBuffer(64, sizeof(int), ComputeBufferType.Append);
        consumeBuffer.SetCounterValue(0);
        consumeBuffer.SetData(new int[] { 97, 98, 99 });
        consumeBuffer.SetCounterValue(3);
        //consume類型結構至關於棧,因此取到的第一個值是99。

        computeShader.SetBuffer(kernelID, "appendBuffer", appendBuffer);
        computeShader.SetBuffer(kernelID, "consumeBuffer", consumeBuffer);
        computeShader.Dispatch(kernelID, 1, 1, 1);
        //單個線程組的大小爲8,定義了1個線程組。也就是說會返回8個數據。

        var countBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
        ComputeBuffer.CopyCount(appendBuffer, countBuffer, 0);
        //經過這個方法拿到第一個數據。

        int[] counter = new int[1] { 0 };
        countBuffer.GetData(counter);

        int count = counter[0];

        Debug.Log("count: " + count);

        var data = new int[count];
        appendBuffer.GetData(data);

        Debug.Log("data length: " + data.Length);

        for (int i = 0; i < data.Length; i++)
        {
            Debug.Log(data[i]);
        }

        consumeBuffer.Release();
        consumeBuffer.Dispose();

        appendBuffer.Release();
        appendBuffer.Dispose();

        countBuffer.Release();
        countBuffer.Dispose();
    }
}

 

 

compute shader:ui

#pragma kernel CSMain

AppendStructuredBuffer<int> appendBuffer;
ConsumeStructuredBuffer<int> consumeBuffer;

[numthreads(8,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    if (id.x == 2)
    {
        int value = consumeBuffer.Consume();
        appendBuffer.Append(value);
    }

    if (id.x > 2)
    {
        appendBuffer.Append(id.x);
    }
}

 

 

傳入的線程組是8,1,1。而且Dispatch只運行了一個線程組,因此每一次傳入id的x值依次爲0,1,2,3,4,5,6,7spa

在id是2的時候讀consume裏的值,因此第一個是99.線程

最終輸出:99,3,4,5,6,7。3d

相關文章
相關標籤/搜索