Sharing a texture between a compute shader and a pixel shader?

Hi all,

I’m trying to compute a 3D texture in a compute shader, then use it in a pixel shader, hopefully avoiding memory transfer between GPU and CPU. Seems like I’m missing something obvious… My compute shader looks like:

#pragma kernel CSMain
RWTexture3D<float4> Result;

[numthreads(1,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
	Result[id.xyz] = float4(1, 0, 0, 1);
}

So just setting red in the whole texture, which I’m hoping to use this way:

CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 5.0

sampler3D _Density;

struct Input {		
};

void surf (Input IN, inout SurfaceOutputStandard o) {
	fixed3 c = tex3D(_Density, int3(0, 0, 0));
	o.Albedo = c.rgb;
}
ENDCG

So just getting one pixel to color the entire mesh. Finally, at the C# level:

    Texture t = new Texture3D(16, 16, 16, TextureFormat.RGBAFloat, false);        
    int kernel = shader.FindKernel("CSMain");

    shader.SetTexture(kernel, "Result", t);
    shader.Dispatch(kernel, 16, 16, 16);

    GetComponent<MeshRenderer>().sharedMaterial.SetTexture("_Density", t);

No compiler or run-time error, but my mesh stays white instead of red… Probably missing something obvious. Any hints?

Thanks!

ST

… and a couple of hours later, found the answer if anybody needs it. The trick is to use a “RenderTexture” instead, so in my case, the C# code becomes:

RenderTexture t = new RenderTexture(16, 16, 16, RenderTextureFormat.ARGBFloat);
t.dimension = UnityEngine.Rendering.TextureDimension.Tex3D;
t.enableRandomWrite = true;
t.Create();
GetComponent<MeshRenderer>().sharedMaterial.SetTexture("_Density", t);
int kernel = shader.FindKernel("CSMain");
shader.SetTexture(kernel, "Result", t);
shader.Dispatch(kernel, 16, 16, 16);       

I put the texture association with the pixel shader before the actual call to the compute buffer, which still works. It seems to indicate that indeed they share the same space in memory and that there’s no CPU interaction here.