RTMP/Assets/TestScreenCapturer.cs

74 lines
2.6 KiB
C#
Raw Normal View History

2024-11-18 14:20:44 +08:00
using System.Diagnostics;
using System.IO;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
using Debug = UnityEngine.Debug;
namespace ZC
{
public class TestScreenCapturer : MonoBehaviour
{
private NativeArray<byte> _data;
private RenderTexture _mainTargetTexture;
private AsyncGPUReadbackRequest _asyncGPUReadbackRequest;
private bool _start = false;
private void Start()
{
var main = Camera.main;
this._mainTargetTexture = main.targetTexture;
_data = new NativeArray<byte>(this._mainTargetTexture.width * this._mainTargetTexture.height * 3, Allocator.Persistent);
}
private void Update()
{
if (this._start)
{
if (_asyncGPUReadbackRequest.done && !this._asyncGPUReadbackRequest.hasError)
{
this._asyncGPUReadbackRequest = AsyncGPUReadback.RequestIntoNativeArray(ref this._data, this._mainTargetTexture, 0, GraphicsFormat.B8G8R8_UNorm, this.Callback);
}
}
if (Input.GetKeyDown(KeyCode.D))
{
this._asyncGPUReadbackRequest = AsyncGPUReadback.RequestIntoNativeArray(ref this._data, this._mainTargetTexture, 0, GraphicsFormat.B8G8R8_UNorm, this.Callback);
this._start = true;
}
for (var i = 0; i < 10_00; i++)
{
Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(Mathf.Sqrt(12.3f)))))));
}
}
private void OnDestroy()
{
if (_data.IsCreated)
_data.Dispose();
}
private void Callback(AsyncGPUReadbackRequest obj)
{
if (obj.hasError)
{
return;
}
if (obj.done)
{
Debug.Log(Time.frameCount);
Profiler.BeginSample("CallBack");
var encodeNativeArrayToJPG = ImageConversion.EncodeNativeArrayToJPG(this._data, GraphicsFormat.R8G8B8_UNorm, (uint)this._mainTargetTexture.width, (uint)this._mainTargetTexture.height);
File.WriteAllBytes(@"D:\test.jpg", encodeNativeArrayToJPG.ToArray());
Bitmap.SaveToDisk("D:\\test1.bmp", this._data,0,this._data.Length,this._mainTargetTexture.width,this._mainTargetTexture.height);
encodeNativeArrayToJPG.Dispose();
Profiler.EndSample();
}
}
}
}