How do I read StaticMesh triangle data from GPU memory to CPU memory?

Hi MartinNilsson

I had to a similar task recently whilst investigating multithreading. Take a look at TFutures (promises) and TFunctions (Lambdas). They may help with your problem.
Execute a TFunction on the GPU thread and return the data you want back to the game thread through the TFuture.
Once you understand them, TFutures and TFunctions are extremely powerful

Basically a future works the same as a return value, except that it doesn’t need to be populated immediately. It gives the program a “promise” that it will return data eventually.

I will provide a simple example, but note I only wrote the code, I didn’t test it. But there are other examples online.

//HEADER
//-----------------------

//Variable to hold the return data from the GPU thread.
//Replace "int" with the desired datatype to return. 
TFuture<int> dataToReturnToGameThread; 


//Function to trigger the logic
void RunGPUThreadTask();

//Function to call once the operation is complete
void OnReturnToCPU();

//Function to execute on the GPU with a lambda used to return back to the Game thread
TFuture<int> FunctionToRunOnGPU(const UObject* outer, TFunction<void()>completionLambda);

//CPP
//-----------------------

void MyClass::RunGPUThreadTask()
{
	dataToReturnToGameThread = FunctionToRunOnGPU(this, [this]()
	{
		//Check to see if the data has been populated
		if(dataToReturnToGameThread.IsValid())
		{
			//Return the data back to the CPU thread
			AsyncTask(ENamedThreads::GameThread, [this]()
			{
				//Log to state that we have returned to the Game Thread
				UE_LOG(LogTemp, Log, TEXT("Successfully returned to Game Thread with %d"), dataToReturnToGameThread.Get());
				
				//Call the function to work with the returned data
				OnReturnToCPU()
			});
		}
	});
}


TFuture<int> MyClass::FunctionToRunOnGPU(const UObject* outer, TFunction<void()>completionLambda)
{
	//Execute this directly on a GPU thread
	return Async(EAsyncExecution::ThreadPool, [=]()
	{
		UE_LOG(LogTemp, Log, TEXT("Operating on GPU Thread"));

		//Any logic here that you want to execute on the GPU
		int dataToReturn = 10;

		//Return any data you want back to the Game Thread, which will then be accessable through the future
		return dataToReturn;
	
	}, completionLambda );
}


void MyClass::OnReturnToCPU
{
	//Do what ever you want with the data
int myInt = dataToReturnToGameThread.Get(); //Used to access the data

    }

Unfortunately, I do not know how to access the triangle data, but perhaps this will be a good start in at least knowing that you are working on GPU / CPU.

Hope this helps.

Good luck!

Alex