SerializableProperty.cs 17 KB

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