BarcodeDecoder.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using UnityEngine;
  2. class BarcodeDecoder : MonoBehaviour
  3. {
  4. [SerializeField] int Row;
  5. [SerializeField] int Column;
  6. [SerializeField] ComputeShader Shader;
  7. #if UNITY_2020_1_OR_NEWER
  8. GraphicsBuffer readbackBuffer_;
  9. #else
  10. ComputeBuffer readbackBuffer_;
  11. #endif
  12. int kernelIndex_;
  13. Color[] data_;
  14. private void Awake()
  15. {
  16. int count = Row * Column;
  17. int stride = sizeof(float) * 4;
  18. #if UNITY_2020_1_OR_NEWER
  19. readbackBuffer_ =
  20. new GraphicsBuffer(GraphicsBuffer.Target.Structured, count, stride);
  21. #else
  22. readbackBuffer_ =
  23. new ComputeBuffer(count, stride, ComputeBufferType.Structured);
  24. #endif
  25. data_ = new Color[count];
  26. kernelIndex_ = Shader.FindKernel("Read");
  27. }
  28. private void OnDestroy()
  29. {
  30. readbackBuffer_.Dispose();
  31. }
  32. public int GetValue(Texture texture)
  33. {
  34. return Decode(texture);
  35. }
  36. int Decode(Texture source)
  37. {
  38. Shader.SetTexture(kernelIndex_, "Source", source);
  39. Shader.SetInt("Row", Row);
  40. Shader.SetInt("Column", Column);
  41. Shader.SetBuffer(kernelIndex_, "Result", readbackBuffer_);
  42. Shader.Dispatch(kernelIndex_, Row, Column, 1);
  43. readbackBuffer_.GetData(data_);
  44. int value = 0;
  45. for (int i = 0; i < data_.Length; i++)
  46. {
  47. if (data_[i].grayscale > 0.5)
  48. value += 1 << i;
  49. }
  50. return value;
  51. }
  52. }