Writing to 3D texture in Compute Shader

Updated on September 26, 2017 in [A] Shaders
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on September 26, 2017

I’ve been trying to get into writing compute shaders for Unity and I cannot for the life of me figure out why I cant write to a 3D texture but I can write to a 2D texture. This is a simplified example of what I’m trying to do that should output a 8x8x8 grid of 1’s but instead returns 0’s, meaning the texture isnt being set. It works if components are changed to 2D instead.

 

 

 

Component

 

 

 

 
 
 
using UnityEngine;
 
 
 
public class ComputeExample : MonoBehaviour {
 
 
 
public ComputeShader s;
 enum Kernels { SetGrid, TexToArray }
 
 
 
void Start() {
    RenderTexture grid = new RenderTexture(8, 8, 24);
     grid.enableRandomWrite = true;
     grid.dimension = UnityEngine.Rendering.TextureDimension.Tex3D;
     grid.volumeDepth = 8;
     grid.Create();
 
 
 
    ComputeBuffer buffer = new ComputeBuffer(8 * 8 * 8, sizeof(float));
 
 
 
    s.SetTexture((int)Kernels.SetGrid, "TestGrid", grid);
     s.Dispatch((int)Kernels.SetGrid, 1, 1, 1);
 
 
 
     s.SetTexture((int)Kernels.TexToArray, "TestGrid", grid);
     s.SetBuffer((int)Kernels.TexToArray, "ArrayOutput", buffer);
     s.Dispatch((int)Kernels.TexToArray, 1, 1, 1);
 
 
 
    float[] temp = new float[8 * 8 * 8];
     buffer.GetData(temp);
 
 
 
    string tempData = "Grid Contents:";
 
 
 
    for (int i = 0; i < 8; i++) {
         tempData += "\n\nDepth " + (i + 1);
         for (int j = 0; j < 8; j++) {
             tempData += "\n";
             for (int k = 0; k < 8; k++)
                 tempData += (temp[i + j * 8 + k * 8 * 8]) + " ";
         }
     }
     Debug.Log(tempData);
 
 
 
    grid.Release();
     buffer.Release();
     }
}
 
 
 

 

 

 

ComputeShader

 

 

 

 
 
 
#pragma kernel SetGrid
#pragma kernel TexToArray
 
 
 
int gs;
RWStructuredBuffer ArrayOutput;
RWTexture3D TestGrid;
 
 
 
[numthreads(8,8,8)]
void SetGrid (int3 id : SV_DispatchThreadID)
{
     TestGrid[id] = 1;
}
 
 
 
[numthreads(8, 8, 8)]
void TexToArray(int3 id : SV_DispatchThreadID)
{
     ArrayOutput[id.x + gs * id.y + gs * gs * id.z] = TestGrid[id];
}
 
 
 
  • Liked by
Reply