SerializableProperty.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Runtime.CompilerServices;
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Serialization
  10. * @{
  11. */
  12. /// <summary>
  13. /// Allows you to transparently retrieve and set values of an entry, whether that entry is an object field or
  14. /// an array/list/dictionary entry.
  15. /// </summary>
  16. public sealed class SerializableProperty : ScriptObject
  17. {
  18. /// <summary>
  19. /// Object field types support by the serializable property.
  20. /// </summary>
  21. public enum FieldType
  22. {
  23. Int,
  24. Float,
  25. Bool,
  26. String,
  27. Color,
  28. Vector2,
  29. Vector3,
  30. Vector4,
  31. GameObjectRef,
  32. Resource,
  33. Object,
  34. Array,
  35. List,
  36. Dictionary,
  37. RRef,
  38. }
  39. public delegate object Getter();
  40. public delegate void Setter(object value);
  41. private FieldType type;
  42. private Type internalType;
  43. private Getter getter;
  44. private Setter setter;
  45. /// <summary>
  46. /// Constructor for internal use by the native code.
  47. /// </summary>
  48. private SerializableProperty()
  49. { }
  50. /// <summary>
  51. /// Creates a new serializable property.
  52. /// </summary>
  53. /// <param name="type">Type of data the property contains.</param>
  54. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  55. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  56. /// <param name="setter">Method that allows you to set contents of the property</param>
  57. public SerializableProperty(FieldType type, Type internalType, Getter getter, Setter setter)
  58. {
  59. this.type = type;
  60. this.internalType = internalType;
  61. this.getter = getter;
  62. this.setter = setter;
  63. Internal_CreateInstance(this, internalType);
  64. }
  65. /// <summary>
  66. /// Finalizes construction of the serializable property. Must be called after creation.
  67. /// </summary>
  68. /// <param name="type">Type of data the property contains.</param>
  69. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  70. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  71. /// <param name="setter">Method that allows you to set contents of the property</param>
  72. internal void Construct(FieldType type, Type internalType, Getter getter, Setter setter)
  73. {
  74. this.type = type;
  75. this.internalType = internalType;
  76. this.getter = getter;
  77. this.setter = setter;
  78. }
  79. /// <summary>
  80. /// Returns type of data the property contains.
  81. /// </summary>
  82. public FieldType Type
  83. {
  84. get { return type; }
  85. }
  86. /// <summary>
  87. /// Returns type of data the property contains, as C# type.
  88. /// </summary>
  89. public Type InternalType
  90. {
  91. get { return internalType; }
  92. }
  93. /// <summary>
  94. /// Is the containing type a value type (true), or a reference type (false).
  95. /// </summary>
  96. public bool IsValueType
  97. {
  98. get { return internalType.IsValueType; }
  99. }
  100. /// <summary>
  101. /// Retrieves the value contained in the property.
  102. /// </summary>
  103. /// <typeparam name="T">Type of the value to retrieve. Caller must ensure the type matches the property type.</typeparam>
  104. /// <returns>Value of the property.</returns>
  105. public T GetValue<T>()
  106. {
  107. if (!typeof(T).IsAssignableFrom(internalType))
  108. throw new Exception("Attempted to retrieve a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  109. return (T)getter();
  110. }
  111. /// <summary>
  112. /// Changes the value of the property.
  113. /// </summary>
  114. /// <typeparam name="T">Type of the value to set. Caller must ensure the type matches the property type.</typeparam>
  115. /// <param name="value">New value to assign to the property.</param>
  116. public void SetValue<T>(T value)
  117. {
  118. if (!typeof(T).IsAssignableFrom(internalType))
  119. throw new Exception("Attempted to set a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  120. setter(value);
  121. }
  122. /// <summary>
  123. /// Returns a serializable object wrapper around the value contained in the property.
  124. /// </summary>
  125. /// <returns>Serializable object wrapper around the value contained in the property.</returns>
  126. public SerializableObject GetObject()
  127. {
  128. if (type != FieldType.Object)
  129. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  130. return Internal_CreateObject(mCachedPtr, this);
  131. }
  132. /// <summary>
  133. /// Returns a serializable array around the value contained in the property. Caller must ensure the property
  134. /// contains an array.
  135. /// </summary>
  136. /// <returns>Serializable array around the value contained in the property.</returns>
  137. public SerializableArray GetArray()
  138. {
  139. if (type != FieldType.Array)
  140. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  141. return Internal_CreateArray(mCachedPtr, this);
  142. }
  143. /// <summary>
  144. /// Returns a serializable list around the value contained in the property. Caller must ensure the property
  145. /// contains a list.
  146. /// </summary>
  147. /// <returns>Serializable list around the value contained in the property.</returns>
  148. public SerializableList GetList()
  149. {
  150. if (type != FieldType.List)
  151. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  152. return Internal_CreateList(mCachedPtr, this);
  153. }
  154. /// <summary>
  155. /// Returns a serializable dictionary around the value contained in the property. Caller must ensure the property
  156. /// contains a dictionary.
  157. /// </summary>
  158. /// <returns>Serializable dictionary around the value contained in the property.</returns>
  159. public SerializableDictionary GetDictionary()
  160. {
  161. if (type != FieldType.Dictionary)
  162. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  163. return Internal_CreateDictionary(mCachedPtr, this);
  164. }
  165. /// <summary>
  166. /// Creates a new instance of the type wrapped by this property.
  167. /// </summary>
  168. /// <typeparam name="T">Type of the object to create. Caller must ensure the type matches the property type and that
  169. /// the property wraps an object.</typeparam>
  170. /// <returns>A new instance of an object of type <typeparamref name="T"/>.</returns>
  171. public T CreateObjectInstance<T>()
  172. {
  173. if (type != FieldType.Object)
  174. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  175. return (T)Internal_CreateManagedObjectInstance(mCachedPtr);
  176. }
  177. /// <summary>
  178. /// Creates a new instance of the array wrapped by this property. Caller must ensure this property contains an array.
  179. /// </summary>
  180. /// <param name="lengths">Size of each dimension of the array. Number of dimensions must match the number
  181. /// of dimensions in the array wrapped by this property.</param>
  182. /// <returns>A new array containing the same element type as the array wrapped by this property, of
  183. /// <paramref name="lengths"/> sizes.</returns>
  184. public Array CreateArrayInstance(int[] lengths)
  185. {
  186. if (type != FieldType.Array)
  187. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  188. return Internal_CreateManagedArrayInstance(mCachedPtr, lengths);
  189. }
  190. /// <summary>
  191. /// Creates a new instance of the list wrapped by this property. Caller must ensure this property contains a list.
  192. /// </summary>
  193. /// <param name="length">Size of the list.</param>
  194. /// <returns>A new list containing the same element type as the list wrapped by this property, of
  195. /// <paramref name="length"/> size.</returns>
  196. public IList CreateListInstance(int length)
  197. {
  198. if (type != FieldType.List)
  199. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  200. return Internal_CreateManagedListInstance(mCachedPtr, length);
  201. }
  202. /// <summary>
  203. /// Creates a new instance of the dictionary wrapped by this property. Caller must ensure this property contains
  204. /// a dictionary.
  205. /// </summary>
  206. /// <returns>A new dictionary containing the same key/value types as the dictionary wrapped by this property.
  207. /// </returns>
  208. public IDictionary CreateDictionaryInstance()
  209. {
  210. if (type != FieldType.Dictionary)
  211. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  212. return Internal_CreateManagedDictionaryInstance(mCachedPtr);
  213. }
  214. /// <summary>
  215. /// Helper method used for finding child properties of the specified property, using a property path.
  216. /// <see cref="SerializableObject.FindProperty(string)"/>.
  217. /// </summary>
  218. /// <param name="pathElements">Path elements representing field names and keys to look for.</param>
  219. /// <param name="elementIdx">Index in the <paramref name="pathElements"/> array to start the search at.</param>
  220. /// <returns>Property representing the final path element, or null if not found (array index is out of range, or
  221. /// property with that path doesn't exist).</returns>
  222. internal SerializableProperty FindProperty(PropertyPathElement[] pathElements, int elementIdx)
  223. {
  224. switch (type)
  225. {
  226. case FieldType.Object:
  227. {
  228. SerializableObject childObject = GetObject();
  229. return childObject.FindProperty(pathElements, elementIdx);
  230. }
  231. case FieldType.Array:
  232. {
  233. SerializableArray childArray = GetArray();
  234. return childArray.FindProperty(pathElements, elementIdx);
  235. }
  236. case FieldType.List:
  237. {
  238. SerializableList childList = GetList();
  239. return childList.FindProperty(pathElements, elementIdx);
  240. }
  241. case FieldType.Dictionary:
  242. {
  243. SerializableDictionary childDictionary = GetDictionary();
  244. return childDictionary.FindProperty(pathElements, elementIdx);
  245. }
  246. }
  247. return null;
  248. }
  249. [MethodImpl(MethodImplOptions.InternalCall)]
  250. private static extern void Internal_CreateInstance(SerializableProperty instance, Type type);
  251. [MethodImpl(MethodImplOptions.InternalCall)]
  252. private static extern SerializableObject Internal_CreateObject(IntPtr nativeInstance, object managedInstance);
  253. [MethodImpl(MethodImplOptions.InternalCall)]
  254. private static extern SerializableArray Internal_CreateArray(IntPtr nativeInstance, object managedInstance);
  255. [MethodImpl(MethodImplOptions.InternalCall)]
  256. private static extern SerializableList Internal_CreateList(IntPtr nativeInstance, object managedInstance);
  257. [MethodImpl(MethodImplOptions.InternalCall)]
  258. private static extern SerializableDictionary Internal_CreateDictionary(IntPtr nativeInstance, object managedInstance);
  259. [MethodImpl(MethodImplOptions.InternalCall)]
  260. private static extern object Internal_CreateManagedObjectInstance(IntPtr nativeInstance);
  261. [MethodImpl(MethodImplOptions.InternalCall)]
  262. private static extern Array Internal_CreateManagedArrayInstance(IntPtr nativeInstance, int[] lengths);
  263. [MethodImpl(MethodImplOptions.InternalCall)]
  264. private static extern IList Internal_CreateManagedListInstance(IntPtr nativeInstance, int length);
  265. [MethodImpl(MethodImplOptions.InternalCall)]
  266. private static extern IDictionary Internal_CreateManagedDictionaryInstance(IntPtr nativeInstance);
  267. [MethodImpl(MethodImplOptions.InternalCall)]
  268. private static extern object Internal_CloneManagedInstance(IntPtr nativeInstance, object original);
  269. /// <summary>
  270. /// Converts a C# type into Banshee-specific serialization type.
  271. /// </summary>
  272. /// <param name="internalType">C# to convert.</param>
  273. /// <returns>Banshee-specific serialization type. Throws an exception if matching type cannot be found.</returns>
  274. public static FieldType DetermineFieldType(Type internalType)
  275. {
  276. if (!internalType.IsArray)
  277. {
  278. if (internalType == typeof (Byte))
  279. return FieldType.Int;
  280. else if (internalType == typeof (SByte))
  281. return FieldType.Int;
  282. else if (internalType == typeof (Int16))
  283. return FieldType.Int;
  284. else if (internalType == typeof (UInt16))
  285. return FieldType.Int;
  286. else if (internalType == typeof (Int32))
  287. return FieldType.Int;
  288. else if (internalType == typeof (UInt32))
  289. return FieldType.Int;
  290. else if (internalType == typeof (Int64))
  291. return FieldType.Int;
  292. else if (internalType == typeof (UInt64))
  293. return FieldType.Int;
  294. else if (internalType == typeof (bool))
  295. return FieldType.Bool;
  296. else if (internalType == typeof (float))
  297. return FieldType.Float;
  298. else if (internalType == typeof (double))
  299. return FieldType.Float;
  300. else if (internalType == typeof (string))
  301. return FieldType.String;
  302. else if (internalType == typeof (Vector2))
  303. return FieldType.Vector2;
  304. else if (internalType == typeof (Vector3))
  305. return FieldType.Vector3;
  306. else if (internalType == typeof (Vector4))
  307. return FieldType.Vector4;
  308. else if (internalType == typeof(Quaternion))
  309. return FieldType.Vector4;
  310. else if (internalType == typeof (Color))
  311. return FieldType.Color;
  312. else if (internalType.IsSubclassOf(typeof (GameObject)))
  313. return FieldType.GameObjectRef;
  314. else if (internalType.IsSubclassOf(typeof (Resource)))
  315. return FieldType.Resource;
  316. else if (internalType.IsSubclassOf(typeof (RRefBase)))
  317. return FieldType.RRef;
  318. else if (internalType.IsGenericType)
  319. {
  320. Type genericType = internalType.GetGenericTypeDefinition();
  321. if (genericType == typeof (List<>))
  322. return FieldType.List;
  323. else if (genericType == typeof (Dictionary<,>))
  324. return FieldType.Dictionary;
  325. else if (genericType == typeof(RRef<>))
  326. return FieldType.RRef;
  327. // Shouldn't happen because native code should only supply us with supported types
  328. throw new Exception("Cannot determine field type. Found an unsupported generic type.");
  329. }
  330. // Otherwise the type must be an object, unless some error occurred
  331. return FieldType.Object;
  332. }
  333. return FieldType.Array;
  334. }
  335. }
  336. /** @} */
  337. }