A while ago I was successfully able to implement RWStructuredBuffer
s in vert frag shaders with #pragma target 5.0
and #pragma only_renderers d3d11
. It took some stumbling to discover you need RWStructuredBuffer<MyStruct> myBuff : register(u1)
and then in C# Graphics.SetRandomWriteTarget(1, myComputeBuffer, true);
etc…
But I can’t get RWTexture2D<float4>
to work and there’s no way to figure out what’s wrong unless you magically already know.
In C# I have:
m_paintAccumulationRT = new RenderTexture(rtWH_x, rtWH_y, 24, RenderTextureFormat.ARGB32);// Must be ARGB32 but will get automagically converted to float or float4 or int or half, from your shader code declaration.
m_paintAccumulationRT.name = _MainTexInternal;
m_paintAccumulationRT.enableRandomWrite = true;
m_paintAccumulationRT.Create();
Then when I render, also C#:
m_paintAccumulatorCB.DrawMesh(m_testMeshToDraw.GetComponent<SkinnedMeshRenderer>().sharedMesh,
Matrix4x4.TRS(m_testMeshToDraw.position, m_testMeshToDraw.rotation, m_testMeshToDraw.localScale),
m_2DSprayAccumulator_mat,
0,
0);
Then my vertex fragment CG shader code:
uniform RWTexture2D<float4> _MainTexInternal;// : register(u2);
//...
#pragma target 5.0
#pragma only_renderers d3d11
//...
float4 frag(v2f i) : SV_Target
{
int coordx = int((mainUV.x)*2048);
int coordy = int((mainUV.y)*2048);
int2 mainUVRWT = int2(coordx,coordy);
float4 prevColor = _MainTexInternal[mainUVRWT];// Doesn't work, but maybe it's not meant to be read this way.
//...
_MainTexInternal[mainUVRWT] += outColor;
return _MainTexInternal[mainUVRWT]; // THIS WORKS, but is reset every frame (ie no "paint accumulation" is happening despite the +=)
}
The thing is, if I look at my m_paintAccumulationRT
in C# / unity, no matter what I try in the shader or c#, I only see black, or sometimes white.
Also note that I cannot use Blit. Don’t recommend Blit. I need to write to a RenderTexture from a Mesh in the world (inlcuding backfaces). I also know I can use compute shaders, no need to recommend those.
Has someone ever figured this out in unity? Does anyone have an actual working example? Or I’ll just give up and use RWStructuredBuffers.