Hello!
I’ve been attempting to dig into compute shaders and have been getting some weird results when trying to write to render textures via compute shader. I’ve stripped everything back to what seems like its simplest possible form, a compute shader that just copies an input texture to a render texture, but I’m still running into the same issue.
Input on the left, output on the right.
Output image is a 2048x2048 render texture (see below), but the compute shader only seems to be able to write to the first 4x4 pixels regardless of anything that I do. It’s almost as if its writing to a 4x4 target which is then being blit to my output render texture.
Code below, as you can see there’s really not very much going on here (the compute buffer is just there to double check that the shader is executing more than 16 times), so I’m sure I’m just missing something incredibly obvious, but any help would be greatly appreciated.
Running Unity 2019.2.16f1 on Mac OS Mojave using Metal.
using UnityEngine;
public class CopyTextureWithComputerShader : MonoBehaviour
{
public Texture2D inputTexture;
public RenderTexture outputRenderTexture;
public ComputeShader computeShader;
public void Start()
{
var tempOutputTexture = RenderTexture.GetTemporary(2048, 2048);
tempOutputTexture.enableRandomWrite = true;
var kernelID = computeShader.FindKernel("CopyTexture");
var buffer = new ComputeBuffer(1024, 4);
computeShader.SetTexture(kernelID,"InputTexture", inputTexture);
computeShader.SetTexture(kernelID,"OutputRenderTexture", tempOutputTexture);
computeShader.SetBuffer(kernelID,"OutputBuffer", buffer);
computeShader.Dispatch(kernelID, tempOutputTexture.width/32,tempOutputTexture.height/32,1);
var results = new float[1024];
buffer.GetData(results);
foreach ( var item in results)
{
Debug.Log(item);
}
buffer.Release();
Graphics.Blit(tempOutputTexture,outputRenderTexture);
}
}
#pragma kernel CopyTexture
Texture2D<float4> InputTexture;
RWTexture2D<float4> OutputRenderTexture;
RWStructuredBuffer<float> OutputBuffer;
[numthreads(32,32,1)]
void CopyTexture (uint3 id : SV_DispatchThreadID)
{
OutputBuffer[id.x] = InputTexture[id.xy].r;
OutputRenderTexture[id.xy] = InputTexture[id.xy];
}