Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created April 27, 2022 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/74744dd61c81d7a675c76fc9fda4d67d to your computer and use it in GitHub Desktop.
Save phosphoer/74744dd61c81d7a675c76fc9fda4d67d to your computer and use it in GitHub Desktop.
AsyncGPUReadback Class
using Unity.Collections;
using UnityEngine;
using UnityEngine.Rendering;
[System.Serializable]
public class RenderToCPU
{
public event System.Action ErrorOccurred;
public int Width => _renderTarget.width;
public int Height => _renderTarget.height;
private RenderTexture _renderTarget;
private AsyncGPUReadbackRequest _requestedFrame;
private bool _isFrameRequested = false;
private float[] _colorBuffer;
public RenderToCPU(RenderTexture targetTexture)
{
_renderTarget = targetTexture;
_colorBuffer = new float[_renderTarget.width * _renderTarget.height];
System.Array.Clear(_colorBuffer, 0, _colorBuffer.Length);
}
public float GetColorClamped(int x, int y)
{
x = Mathf.Clamp(x, 0, Width - 1);
y = Mathf.Clamp(y, 0, Height - 1);
float color = GetColor(x, y);
return color;
}
public float GetColor(int x, int y)
{
return _colorBuffer[x + y * _renderTarget.width];
}
public void Update()
{
// If we have a request frame, check the status
if (_isFrameRequested)
{
if (_requestedFrame.hasError)
{
_isFrameRequested = false;
ErrorOccurred?.Invoke();
Debug.LogWarning("Failed to read gpu texture");
}
// If the frame is done, we can grab the pixel data
else if (_requestedFrame.done)
{
_isFrameRequested = false;
NativeArray<float> colors = _requestedFrame.GetData<float>();
colors.CopyTo(_colorBuffer);
}
}
// If we haven't request a frame yet, do so
else
{
_isFrameRequested = true;
_requestedFrame = AsyncGPUReadback.Request(_renderTarget);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment