SerializableArray.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace BansheeEngine
  8. {
  9. public sealed class SerializableArray : ScriptObject
  10. {
  11. private object referencedObject;
  12. private SerializableField.FieldType elementType;
  13. private Type internalElementType;
  14. private int[] dimensions;
  15. public SerializableArray(object obj)
  16. {
  17. Internal_CreateInstance(this, obj);
  18. referencedObject = obj;
  19. }
  20. public int GetDimension(int rank)
  21. {
  22. return dimensions[rank];
  23. }
  24. public SerializableField.FieldType ElementType
  25. {
  26. get { return elementType; }
  27. }
  28. public int Rank
  29. {
  30. get { return rank; }
  31. }
  32. public T GetValue<T>(params int[] indexes)
  33. {
  34. if (typeof(T) != internalElementType)
  35. throw new Exception("Attempted to retrieve a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalElementType);
  36. return (T)Internal_GetValue(mCachedPtr, ArrayIndexesToId(indexes));
  37. }
  38. public void SetValue<T>(T value, params int[] indexes)
  39. {
  40. if (typeof(T) != internalElementType)
  41. throw new Exception("Attempted to set a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalElementType);
  42. Internal_SetValue(mCachedPtr, ArrayIndexesToId(indexes), value);
  43. }
  44. private int ArrayIndexesToId(params int[] indexes)
  45. {
  46. int index = 0;
  47. int prevDimensionSize = 1;
  48. for (int i = dimensions.Length - 1; i >= 0; i--)
  49. {
  50. index += indexes[i] * prevDimensionSize;
  51. prevDimensionSize *= dimensions[i];
  52. }
  53. return index;
  54. }
  55. [MethodImpl(MethodImplOptions.InternalCall)]
  56. private static extern void Internal_CreateInstance(SerializableArray instance, object obj);
  57. [MethodImpl(MethodImplOptions.InternalCall)]
  58. private static extern void Internal_SetValue(IntPtr nativeInstance, int elementId, object value);
  59. [MethodImpl(MethodImplOptions.InternalCall)]
  60. private static extern object Internal_GetValue(IntPtr nativeInstance, int elementId);
  61. }
  62. }