PointCloudData.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Pcx - Point cloud importer & renderer for Unity
  2. // https://github.com/keijiro/Pcx
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. namespace Pcx
  6. {
  7. /// A container class optimized for compute buffer.
  8. public sealed class PointCloudData : ScriptableObject
  9. {
  10. #region Public properties
  11. /// Byte size of the point element.
  12. public const int elementSize = sizeof(float) * 4;
  13. /// Number of points.
  14. public int pointCount {
  15. get { return _pointData.Length; }
  16. }
  17. /// Get access to the compute buffer that contains the point cloud.
  18. public ComputeBuffer computeBuffer {
  19. get {
  20. if (_pointBuffer == null)
  21. {
  22. _pointBuffer = new ComputeBuffer(pointCount, elementSize);
  23. _pointBuffer.SetData(_pointData);
  24. }
  25. return _pointBuffer;
  26. }
  27. }
  28. #endregion
  29. #region ScriptableObject implementation
  30. ComputeBuffer _pointBuffer;
  31. void OnDisable()
  32. {
  33. if (_pointBuffer != null)
  34. {
  35. _pointBuffer.Release();
  36. _pointBuffer = null;
  37. }
  38. }
  39. #endregion
  40. #region Serialized data members
  41. [System.Serializable]
  42. struct Point
  43. {
  44. public Vector3 position;
  45. public uint color;
  46. }
  47. [SerializeField] Point[] _pointData;
  48. #endregion
  49. #region Editor functions
  50. #if UNITY_EDITOR
  51. static uint EncodeColor(Color c)
  52. {
  53. const float kMaxBrightness = 16;
  54. var y = Mathf.Max(Mathf.Max(c.r, c.g), c.b);
  55. y = Mathf.Clamp(Mathf.Ceil(y * 255 / kMaxBrightness), 1, 255);
  56. var rgb = new Vector3(c.r, c.g, c.b);
  57. rgb *= 255 * 255 / (y * kMaxBrightness);
  58. return ((uint)rgb.x ) |
  59. ((uint)rgb.y << 8) |
  60. ((uint)rgb.z << 16) |
  61. ((uint)y << 24);
  62. }
  63. public void Initialize(List<Vector3> positions, List<Color32> colors)
  64. {
  65. _pointData = new Point[positions.Count];
  66. for (var i = 0; i < _pointData.Length; i++)
  67. {
  68. _pointData[i] = new Point {
  69. position = positions[i],
  70. color = EncodeColor(colors[i])
  71. };
  72. }
  73. }
  74. #endif
  75. #endregion
  76. }
  77. }