亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用計算著色器將紋理轉換為浮點值的一維數組

使用計算著色器將紋理轉換為浮點值的一維數組

C#
守候你守候我 2021-06-04 10:41:28
我對計算著色器(通過 Unity 的 DirectCompute)有一個相當簡單的要求。我有一個 128x128 的紋理,我想將該紋理的紅色通道變成一維浮點數組。我需要經常這樣做,所以只是在每個 texel 上做一個 cpu 端 for 循環不會削減它。初始化:    m_outputBuffer = new ComputeBuffer(m_renderTexture.width * m_renderTexture.height, sizeof(float));    m_kernelIndex = m_computeShader.FindKernel("CSMain");這是 C# 方法:/// <summary>/// This method converts the red channel of the given RenderTexture to a/// one dimensional array of floats of size width * height./// </summary>private float[] ConvertToFloatArray(RenderTexture renderTexture){    m_computeShader.SetTexture(m_kernelIndex, INPUT_TEXTURE, renderTexture);    float[] result = new float[renderTexture.width * renderTexture.height];    m_outputBuffer.SetData(result);    m_computeShader.SetBuffer(m_kernelIndex, OUTPUT_BUFFER, m_outputBuffer);    m_computeShader.Dispatch(m_kernelIndex, renderTexture.width / 8, renderTexture.height / 8, 1);    m_outputBuffer.GetData(result);    return result;}以及整個計算著色器:// Each #kernel tells which function to compile; you can have many kernels#pragma kernel CSMain// Create a RenderTexture with enableRandomWrite flag and set it// with cs.SetTextureTexture2D<float4> InputTexture;RWBuffer<float> OutputBuffer;[numthreads(8, 8, 1)]void CSMain(uint3 id : SV_DispatchThreadID){    OutputBuffer[id.x * id.y] = InputTexture[id.xy].r;}C# 方法返回一個預期大小的數組,它通常符合我的預期。然而,即使我的輸入紋理是統一的紅色,仍然會有一些零。
查看完整描述

1 回答

?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

我重新考慮并解決了我自己的問題。答案分為兩部分:我奇怪地組合了 x 和 y 坐標(id.x 和 id.y),并且我使用了錯誤的輸入語義。(SV_GroupThreadID 而不是 SV_DispatchThreadID)


所以這是解決方案。我還翻轉了 y 軸以符合我的直覺。


// Each #kernel tells which function to compile; you can have many kernels

#pragma kernel CSMain


// Create a RenderTexture with enableRandomWrite flag and set it

// with cs.SetTexture

Texture2D<float4> InputTexture;

RWBuffer<float> OutputBuffer;


[numthreads(8, 8, 1)]

void CSMain(uint3 id : SV_DispatchThreadID)

{

    uint w, h;

    InputTexture.GetDimensions(w, h);


    OutputBuffer[id.x + id.y * w] = InputTexture[float2(id.x, h - 1 - id.y)].r;

}


查看完整回答
反對 回復 2021-06-05
  • 1 回答
  • 0 關注
  • 250 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號