I am currently trying to get a compute shader to work (using this as a guide). At the moment id doesn’t do anything interesting, it is only supposed to copy one texture into another. I will later do some modification to the image, but I can’t even get the copying to work correctly. It only ever uses the first row of pixels, but repeats them over the whole image.
Shader:
#pragma kernel CSMain
Texture2D<float4> cTex;
RWTexture2D<float4> rTex;
[numthreads(32,32,1)]
void CSMain (uint2 id : SV_DispatchThreadID) {
rTex[id] = cTex[id];
}
C# to run it:
ComputeShader _cShader;
Texture2D _tex;
RenderTexture _rTex;
//Start
_cShader = Resources.Load<ComputeShader>("TestShader");
_tex = new Texture2D(1920, 1080, TextureFormat.RGBA32, false);
_rTex = new RenderTexture(_tex.width, _tex.height, 0);
_rTex.enableRandomWrite = true;
_rTex.Create();
//Update
_tex.LoadRawTextureData(SomeFunctionThatReturnsByteArray());
int kernel = _cShader.FindKernel("CSMain");
_cShader.SetTexture(kernel, "rTex", _rTex);
_cShader.SetTexture(kernel, "cTex", _tex);
_cShader.Dispatch(kernel, _data.color.width/32, _data.color.height/32, 1);
I also tried an even simpler Shader that should only create an UV gradient, but this also didn’t create what I expected. The Y-Component was always 0.
[numthreads(32,32,1)]
void CSMain(uint2 id : SV_DispatchThreadID) {
rTex[id] = float4(id.x/1920.0f, id.y/1080.0f, 0, 1);
}
Same behaviour with square pot-textures, with different combinations of threads per group and groups per dispatch*, switching x and y in the DispatchID (or even making it uint3 and try z) or when I calculate the index myself using ‘SV_GroupThreadID’ and ‘SV_GroupID’.
(Using Unity 5.2.0f3)
Clearly I am doing something wrong, but I don’t know what, where or how…
*: only difference: if number_of_groups_x * number_of_threads_per_group_x doesn’t add up to the texture’s width, the right side remains blank, but this is to be expected. No equivalent behaviour in Y direction, though