Generate Unordered Access View from UTexture2D or RenderTarget2D

Hi,

I’m wondering if anyone has figured out how write to a rendertarget or UTexture2D from a computeshader via a UAV. Where I am currently sitting is running these on the render thread:

runOnRenderThread(
        [OutputTexture, FeatureLevel](){
            check(IsInRenderingThread());

			FTexture2DRHIRef RHITex = ((FTexture2DResource*)OutputTexture->Resource)->GetTexture2DRHI();
			
			GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("Texture = ") + RHITex->GetName().ToString());

            /*BREAKS HERE with a DX error*/
			FUnorderedAccessViewRHIRef TextureUAV = RHICreateUnorderedAccessView(RHITex.GetReference(), 0);
            
            /* Get global RHI command list */
            FRHICommandListImmediate& RHICmdList = GRHICommandList.GetImmediateCommandList();
        
            /** Compute shader calculation */
            TShaderMapRef<FHoverComputeShader> ComputeShader(GetGlobalShaderMap(FeatureLevel));
            RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
        
            /* Set inputs/outputs and dispatch compute shader */
            ComputeShader->SetSurfaces(RHICmdList, TextureUAV);
            DispatchComputeShader(RHICmdList, *ComputeShader, RHITex->GetSizeX() / 32, RHITex->GetSizeY() / 32, 1);
            ComputeShader->UnbindBuffers(RHICmdList);
        });

OutTexture is a RenderTarget or Texture2D pointer.

I “think” this has something to do with the Flags that UTexture2D or render target pass when generating thier own FTexture2DRHI but coming from a CUDA with OpenGL inter-op I’m not super familiar with the nuances of ComputeShaders.

If anyone has any insight on this would be appreciated. I’ll keep updating as I find things for posterity.

Kind Regards,
Aidan

You have to provide TexCreate_UAV to the texture flags to support calling RHICreateUnorderedAccessView on it later. Presumably this is so drivers can optimize the texture layout based on how it will be accessed.

UTexture doesn’t currently support a way to pass this flag to the creation. You could add a bool property which does it.

Thought that might be the case. Ended up implementing it and have made a pull request: https://github.com/EpicGames/UnrealEngine/pull/4186

have a look at this plugin: GitHub - ValentinKraft/UE4_SortingComputeShader: A compute shader plugin that is capable of sorting positional data in parallel directly on the GPU.