ThinkRGB.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. using UnityEngine.XR.ARFoundation;
  8. using UnityEngine.XR.ARSubsystems;
  9. public class ThinkRGB : MonoBehaviour
  10. {
  11. private ARCameraManager _cameraManager;
  12. private XRCpuImage _lastCpuImage;
  13. public bool RenderUsingYUVPlanes;
  14. private Texture2D _cameraTexture;
  15. // Start is called before the first frame update
  16. void Awake()
  17. {
  18. _cameraManager = FindObjectOfType<ARCameraManager>();
  19. _cameraManager.frameReceived += OnFrameReceived;
  20. }
  21. private void OnFrameReceived(ARCameraFrameEventArgs obj)
  22. {
  23. if (!_cameraManager.TryAcquireLatestCpuImage(out _lastCpuImage))
  24. {
  25. Debug.Log("Failed to acquire latest cpu image.");
  26. return;
  27. }
  28. UpdateCameraTexture(_lastCpuImage);
  29. }
  30. private unsafe void UpdateCameraTexture(XRCpuImage image)
  31. {
  32. var format = TextureFormat.RGBA32;
  33. if (_cameraTexture == null || _cameraTexture.width != image.width || _cameraTexture.height != image.height)
  34. {
  35. _cameraTexture = new Texture2D(image.width, image.height, format, false);
  36. }
  37. var conversionParams = new XRCpuImage.ConversionParams(image, format);
  38. var rawTextureData = _cameraTexture.GetRawTextureData<byte>();
  39. var rawTexturePtr = new IntPtr(rawTextureData.GetUnsafePtr());
  40. try
  41. {
  42. image.Convert(conversionParams, new IntPtr(rawTextureData.GetUnsafePtr()), rawTextureData.Length);
  43. }
  44. finally
  45. {
  46. image.Dispose();
  47. }
  48. _cameraTexture.Apply();
  49. this.GetComponent<RawImage>().texture = _cameraTexture;
  50. }
  51. // Update is called once per frame
  52. void Update()
  53. {
  54. }
  55. }